Javascript 无法获取api路由(node.js,express)
JS noob,我正在尝试学习一门关于node.JS API创建的课程。我做每件事都是照本宣科。这是server.js文件,如课程中所述:Javascript 无法获取api路由(node.js,express),javascript,node.js,Javascript,Node.js,JS noob,我正在尝试学习一门关于node.JS API创建的课程。我做每件事都是照本宣科。这是server.js文件,如课程中所述: const http = require('http'); const app = require('./app'); const normalizePort = val => { const port = parseInt(val, 10); if (isNaN(port)) { return val; } if (por
const http = require('http');
const app = require('./app');
const normalizePort = val => {
const port = parseInt(val, 10);
if (isNaN(port)) {
return val;
}
if (port >= 0) {
return port;
}
return false;
};
const port = normalizePort(process.env.PORT || 3000);
app.set('port', port);
const errorHandler = error => {
if (error.syscall !== 'listen') {
throw error;
}
const address = server.address();
const bind = typeof address === 'string' ? 'pipe ' + address : 'port: ' + port;
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges.');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use.');
process.exit(1);
break;
default:
throw error;
}
};
const server = http.createServer(app);
server.on('error', errorHandler);
server.on('listening', () => {
const address = server.address();
const bind = typeof address === 'string' ? 'pipe ' + address : 'port ' + port;
console.log('Listening on ' + bind);
});
server.listen(port);
我从控制台运行这个服务器,当我将GET请求发送到http://localhost:3000/api/stuff
,我在app.js中指定的路线:
const express = require('express');
const app = express();
app.use('http://localhost:3000/api/stuff', (req, res, next) => {
const stuff = [
{
message: "this is a JSON"
},
{
message: "this is also a JSON"
}
];
res.status(200).json(stuff);
});
My package.json似乎还可以:
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"node": "^15.2.1"
}
}
在app.js中,我尝试了app.get而不是app.use,并将JSON直接生成到res.status(200).JSON()中
我真的怀疑问题出在server.js中,我尝试过摆弄它,但没有用(输入normalizePort()
字符串而不是整数,消除了process.env.port,简化了交换机,它检查端口3000是否空闲)
我当然在SO中检查过类似的问题,但似乎没有任何问题与我的具体问题相匹配
节点——版本
v13.11.0(本课程也基于旧版本)
- 计划
- 权限(包括主机和端口)
- 路径
- 质疑
- 碎片
http://localhost:3000/api/stuff
结果是:
- 方案:
http
- 权威
- 主机:
localhost
- 端口:
3000
- 主机:
- 路径:
/api/stuff
app.use('/api/stuff',
您可以传递的不仅仅是一个简单的字符串。示例可以在中找到。您是否尝试过应用程序。使用('/api/stuff',…
?它很有效!