猿问

NodeJS 错误:无法 GET/ 在 Web 浏览器上运行 url

此类问题已在 Stackoverflow 中被问过几次,但都没有解决我的问题。


这就是为什么我在这里提出我的问题。在浏览器上运行http://localhost:3000/messages时出现错误


无法获取/消息


从下面的代码。任何帮助都会非常好!


服务器.js


var 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)

})


眼眸繁星
浏览 297回答 2
2回答

米脂

尝试 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"  }}因为您没有使用任何视图引擎,所以它不渲染。

互换的青春

修改你的代码是这样的:app.get('/messages', (req, res) => { res.json({msg: 'messages view'}); }); app.get("/", (req, res) => { res.json({message: 'Stay at home'}); });因为您没有使用任何引擎进行前端渲染,例如ejs或pug。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答