簡體   English   中英

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

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

我正在嘗試從 mysql 數據庫中傳遞一些坐標,以便在 map 上進行標記,但無法獲取它們。 我在 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 中提取坐標以便 plot 它們,必須有辦法嗎? 我是否必須構建 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);
      }
    );
  });

我沒有成功讓 output 在 script.js 中運行。 我將在其工作時發布工作代碼。

在瀏覽器控制台中收到一條錯誤消息,提示“未定義要求”

這是因為require不是前端的 API。 它應該是后端的語法(例如nodeJS)。

我是否必須構建 api 並使用 ajax?

如果您想將數據從前端發送到后端。 使用ajax是可能的,但要點是您需要有一個后端服務器(例如使用 nodeJS 的Express模塊)來連接數據庫(例如 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 package。 如果您在全局范圍內有一個中間件(又名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(這是 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。

我不完全理解所有的部分,所以我需要一段時間才能完全理解這一點並能夠自己重新創建它。 旅程的所有部分!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM