为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

眼眸繁星 2022-05-26 15:39:54
此类问题已在 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"

  }

}

因为您没有使用任何视图引擎,所以它不渲染。


查看完整回答
反对 回复 2022-05-26
?
互换的青春

TA贡献1797条经验 获得超6个赞

修改你的代码是这样的:

app.get('/messages', (req, res) => { res.json({msg: 'messages view'}); }); app.get("/", (req, res) => { res.json({message: 'Stay at home'}); });

因为您没有使用任何引擎进行前端渲染,例如ejspug


查看完整回答
反对 回复 2022-05-26
  • 2 回答
  • 0 关注
  • 296 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号