【问题标题】:Require is not defined in console. node.js js mysql要求未在控制台中定义。 node.js js mysql
【发布时间】:2021-05-16 22:44:53
【问题描述】:

我正在尝试从 mysql 数据库中传递一些坐标以在地图上进行标记,但无法获取它们。我在 stackoverflow 上查看了许多类似的问题,但未能找到答案。如果有人能指出我哪里出错了,将不胜感激。

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);
  });
});

然后在我的 script.js 文件中

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

我在浏览器控制台中收到一条错误消息,提示“未定义要求”

我需要弄清楚如何从 mysql 中提取坐标以便绘制它们,一定有办法吗?我必须构建一个 api 并使用 ajax 吗?提前感谢您的帮助。

更新了我的 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);
      }
    );
  });

我未能成功让输出在 script.js 中运行。我会在它工作时发布工作代码。

【问题讨论】:

    标签: javascript mysql node.js json


    【解决方案1】:

    我得到的解决方案如下:

    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);
        }
      );
    });
    
    

    在我的 script.js 文件中,我缺少以下内容

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

    我相信那是 jQuery ajax

    然后在我的 html 的标题中,我需要以下内容

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

    感谢所有帮助我的人。特别是@tsecheukfung01。

    我没有完全理解所有的部分,所以我需要一段时间才能完全理解这一点并能够自己重新创建它。旅程的所有部分!

    【讨论】:

      【解决方案2】:

      我收到一个错误在浏览器中控制台说“require is not defined”

      这是因为require 不是前端的 API。它应该是后端的语法(例如nodeJS)。

      我必须构建一个 api 并使用 ajax 吗?

      如果您想将数据从前端发送到后端。使用ajax 是可能的,但重点是您需要有一个后端服务器(例如,使用Express 模块用于nodeJS)来连接数据库(例如mysql、postgresSQL)。


      2021 年 2 月 14 日更新

      我的做法是使用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
      });
      

      对于CORS问题,可以安装cors包。如果您在全局范围内有一个中间件(又名app.use(cors()))。每次有请求,这个中间件就会运行。

      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')
      })
      

      【讨论】:

      • 谢谢。上面的代码成功地从服务器检索坐标,getListings.js 中的 console.log(results) 是 myql 表中坐标数组的字符串,但它只显示在终端中。我想在 script.js 文件中调用它,使用它,然后在 index.php 中显示它。是 module.exports = {results};部分代码正确吗?我应该用什么代替 var { results } = require('./getListings');在 script.js 文件中?我尝试了一些导入功能,但它们似乎根本不起作用。我会更多地研究 ajax。
      • 再次感谢您的帮助。我尝试了该代码并得到“来源'localhost'已被CORS策略阻止:请求的资源上不存在'Access-Control-Allow-Origin'标头。”我已经使用了 getListings.js 文件,并包含了一个 API,它现在在浏览器中显示一个字符串,我认为这是朝着正确方向迈出的一步!但我仍然无法将其输出到 script.js 文件中以供使用。
      • @walkslowly 所以你现在有一个express 后端服务器,对吧?对于 CORS 问题,您可以为此问题安装 cors 包。检查我更新的答案。
      • @walkslowly 我看到你在编辑,我看到你想出了一个可行的解决方案。我建议您可以通过将您的编辑发布为新答案并勾选它来回答您自己的问题。如果我的帮助确实有帮助,您可以投票赞成我的回答:))。很高兴为您提供帮助
      猜你喜欢
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 2016-12-28
      • 1970-01-01
      相关资源
      最近更新 更多