此类问题已在 Stackoverflow 中被问过几次,但都没有解决我的问题。这就是为什么我在这里提出我的问题。在浏览器上运行http://localhost:3000/messages时出现错误无法获取/消息从下面的代码。任何帮助都会非常好!服务器.jsvar express = require('express')var app = express()app.use(express.static(__dirname))app.get("/messages", (req, res) => { res.render("Hello"); });var server = app.listen(3000, () =>{ console.log('server is listening on port', server.address().port)})
2 回答

米脂
TA贡献1836条经验 获得超3个赞
尝试 res.json 而不是渲染。
app.get("/messages", (req, res) => {
res.json({msg: 'messages view'});
});
app.get("/", (req, res) => {
res.json({msg: 'Welcome home'});
});
Package.json 文件应该是
{
"name": "sample project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
因为您没有使用任何视图引擎,所以它不渲染。

互换的青春
TA贡献1797条经验 获得超6个赞
修改你的代码是这样的:
app.get('/messages', (req, res) => { res.json({msg: 'messages view'}); }); app.get("/", (req, res) => { res.json({message: 'Stay at home'}); });
因为您没有使用任何引擎进行前端渲染,例如ejs或pug。
添加回答
举报
0/150
提交
取消