Require没有在控制台中定义.Node.js .js . mysql. js



我试图通过一些坐标从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);

我在浏览器控制台中得到一个错误,说"require未定义">

我需要弄清楚如何从mysql拉坐标以便绘制它们,必须有一种方法?我必须建立一个api和使用ajax吗?谢谢你的帮助。

已经更新了我的getlisting .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中运行。我将张贴工作代码时,它的工作。

我在浏览器中得到一个错误控制台显示&;require未定义&;

这是因为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(这是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。

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

最新更新