简体   繁体   English

要求未在控制台中定义。 node.js js mysql

[英]Require is not defined in console. node.js js mysql

I am trying to pass some coordinates from mysql database to be marked on a map but am having trouble getting them.我正在尝试从 mysql 数据库中传递一些坐标,以便在 map 上进行标记,但无法获取它们。 i have looked at a number of similar questions on stackoverflow and have not been able to find an answer.我在 stackoverflow 上查看了许多类似的问题,但未能找到答案。 Would appreciate if someone could please point out where i have gone wrong.如果有人能指出我哪里出错了,我将不胜感激。

getListings.js getListings.js

var mysql = require('mysql');

config = {
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'xx',
  port: 'xxxx',
};

var connection = mysql.createConnection(config); 
connection.connect(function (err) {
  if (err) {
    console.log('error connecting:' + err.stack);
  }
  console.log('connected successfully to DB.');

  connection.query('SELECT listing_coords FROM listings', (err, rows) => {
    if (err) throw err;

    console.log('Data received from Db:\n');
    var results = JSON.parse(JSON.stringify(rows));
    module.exports = { results };
    console.log(results);
  });
});

Then in my script.js file i have然后在我的 script.js 文件中我有

var { results } = require('./getListings');
      console.log(results);

I am getting an error in the browser console saying "require is not defined"我在浏览器控制台中收到一条错误消息,提示“未定义要求”

I will need to figure out how to pull the coordinates from mysql in order to plot them, there has to be a way?我需要弄清楚如何从 mysql 中提取坐标以便 plot 它们,必须有办法吗? Do i have to build an api and use ajax?我是否必须构建 api 并使用 ajax? Thanks in advance for any help.提前感谢您的帮助。

have updated my getListings.js file - it now displays in the string of data i need in the browser as a raw data packet更新了我的 getListings.js 文件 - 它现在显示在浏览器中我需要的数据字符串中,作为原始数据包

var mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');

app.use(bodyparser.json());

config = {
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'xx',
  port: 'xxxx',
};

var connection = mysql.createConnection(config); //added the line
connection.connect(function (err) {
  if (err) {
    console.log('error connecting:' + err.stack);
  }
  console.log('connected successfully to DB.');

  app.listen(5000, () => console.log('express server is running at 5000'));

  app.get('/listings', (req, res) => {
    connection.query(
      'SELECT listing_coords FROM listings',
      (err, rows, fields) => {
        if (!err) res.send(rows);
        else console.log(err);
      }
    );
  });

I have been unsuccessful to get the output to run in script.js.我没有成功让 output 在 script.js 中运行。 I will post the working code when its working.我将在其工作时发布工作代码。

I am getting an error in the browser console saying "require is not defined"在浏览器控制台中收到一条错误消息,提示“未定义要求”

It is because require is not an API for frontend.这是因为require不是前端的 API。 It should be the syntax of backend(eg. nodeJS).它应该是后端的语法(例如nodeJS)。

Do i have to build an api and use ajax?我是否必须构建 api 并使用 ajax?

If you wanna to send data from frontend to backend.如果您想将数据从前端发送到后端。 Using ajax is possible but the main point is you need to have a backend server(eg. using Express module for nodeJS) to connect with the database(eg. mysql, postgresSQL).使用ajax是可能的,但要点是您需要有一个后端服务器(例如使用 nodeJS 的Express模块)来连接数据库(例如 mysql,postgresSQL)。


Update on 14 Feb, 2021 2021 年 2 月 14 日更新

My practise for doing this is to use ajax to send a request to the backend server from frontend.我这样做的做法是使用ajax从前端向后端服务器发送请求。

//frontend
$.ajax
  ({
    url: "yourBackendServerUrl", //eg. localhost:8001/listing. Need modification based on your backend setting.
  })
  .done(function(data) {
     console.log(data)  //data should be the result from backend, then you can retrieve the data for frontend usage
});

For the CORS problem, you can install cors package.对于CORS问题,可以安装cors package。 If you have a middleware in the global scope(aka app.use(cors()) ).如果您在全局范围内有一个中间件(又名app.use(cors()) )。 Every time there are request, this middleware will run.每次有请求时,这个中间件就会运行。

var express = require('express')
var cors = require('cors')
var app = express()
 
app.use(cors()) // pay attention to this line of code. 
 
app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})
 
app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

The solution that I got to work is as follows:我开始工作的解决方案如下:

getListings.js (this was nodeJS) getListings.js(这是 nodeJS)

var mysql = require('mysql');
const express = require('express');
const bodyparser = require('body-parser');
var app = express();

app.use(bodyparser.json());

**app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  );
  next();
});**// I believe this is a middleware function

config = {
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'xx',
  port: 'xxxx',
};

var connection = mysql.createConnection(config); //added the line
connection.connect(function (err) {
  if (err) {
    console.log('error connecting:' + err.stack);
  }
  console.log('connected successfully to DB.');
});

app.listen(5000, () => console.log('express server is running at 5000'));// this can be any port that isnt currently in use

app.get('/listings', (req, res) => {
  connection.query(
    'SELECT listing_coords FROM listings',
    (err, rows, fields) => {
      if (!err) res.send(rows);
      else console.log(err);
    }
  );
});

in my script.js file i was missing the following在我的 script.js 文件中,我缺少以下内容

      $.get('http://localhost:5000/listings', function (data, status) {
        console.log('Cords Data', data);

I believe that is the jQuery ajax我相信那是 jQuery ajax

Then in the heading of my html I needed the following然后在我的 html 的标题中,我需要以下内容

  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
 <script type = "module" defer src="script.js"></script>

thanks to everyone that helped me with this.感谢所有帮助我的人。 especially @tsecheukfung01.特别是@tsecheukfung01。

I dont fully understand all of the pieces so it will take me a while to fully understand this and be able to recreate this on my own.我不完全理解所有的部分,所以我需要一段时间才能完全理解这一点并能够自己重新创建它。 All part of the journey!旅程的所有部分!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM