[英]How to set two root endpoints in one file Restful API with node.js & EXPRESS
I have root endpoint who work when users enter the url like this:当用户像这样输入 url 时,我有根端点工作:
http://localhost:8000/?date=2019-10-20&station=41027&daysForward=3 http://localhost:8000/?date=2019-10-20&station=41027&daysForward=3
I want to create second root endpoint in the same file with different query but that did not work.我想用不同的查询在同一个文件中创建第二个根端点,但这不起作用。
My code:我的代码:
// Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')
app.use(cors())
// Server port
var HTTP_PORT = 8000
// Start server
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%",HTTP_PORT))
});
var con = mysql.createConnection({
host: "192.168.1.1",
port: "3456",
user: "user",
password: "pass"
});
var con2 = mysql.createConnection({
host: "192.168.1.1",
port: "3456",
user: "user",
password: "pass"
});
let aladinModel= '';
let aladinModelStations = '';
app.route('/')
.get(function(req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*');
const date = req.query.date;
const station = req.query.station;
const daysForward = req.query.daysForward;
try {
const query = `CALL aladin_surfex.Get_mod_cell_values_meteogram('${date}', ${station}, ${daysForward})`;
con.query(query, function (err, result, fields) {
if (err) throw err;
aladinModel = result;
});
res.json({aladinModel})
} catch(error){
console.log("Error query database!!!");
}
});
app.route('/stations')
.get(function(req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*');
try {
const query2 = `SELECT Station,Ime FROM stations_cells`;
con2.query2(query2, function (err, result2, fields) {
if (err) throw err;
aladinModelStations = result2;
});
res.json({aladinModelStations})
} catch(error){
console.log("Error query database!!!");
}
});
app.use(function(req, res){
res.status(404);
});
I guess this is not the right way to route pages but I hope someone can explain to me with an example how I could fix the code - so when a user enters:我想这不是路由页面的正确方法,但我希望有人可以通过一个示例向我解释我如何修复代码 - 所以当用户输入时:
http://localhost:3000/stations
the data should be loaded.应该加载数据。
I see this error when I try to open this link.当我尝试打开此链接时看到此错误。
[nodemon] starting `node server.js localhost:8000`
Server running on port 8000
Error query database!!!
This query这个查询
SELECT station, ime
FROM stations_cells
on the second root point is fine.在第二个根点上很好。 I try to
SELECT
with HeidiSQL and database return the data values?我尝试用
SELECT
和数据库返回数据值 SELECT?
Where is the problem for the second root point?第二个根点的问题在哪里?
That might not be the case, but here's the suggestion (which doesn't fit in comment section)情况可能并非如此,但这是建议(不适合评论部分)
app.route('/')
.get(function(req, res) {
// omitted
});
app.route('/stations')
.get(function(req, res) {
// omitted
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.