Nodejs express模板问题:为毛在routes里面的js不能用JSON方法,用了就报错
Nodejs express模板问题:为毛在routes里面的js不能用JSON方法,用了就报错
很不习惯ing
Node.js Express 模板问题:为什么在 routes 文件中的 JavaScript 不能使用 JSON 方法,用了就报错?
在使用 Node.js 和 Express 开发 Web 应用时,你可能会遇到一个常见的问题:在 routes
文件中尝试使用 JSON 方法(如 res.json()
或 req.body
),结果却出现了错误。这通常是因为你没有正确地设置中间件来解析 JSON 数据。
示例问题描述
假设你有一个简单的 Express 应用,其中 routes/index.js
文件如下:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.json({ message: 'Hello World' });
});
module.exports = router;
当你启动应用并访问该路由时,你可能会看到类似于以下的错误:
TypeError: res.json is not a function
或者,如果你试图解析请求体中的 JSON 数据:
router.post('/submit', (req, res) => {
console.log(req.body);
res.send('Data received');
});
如果请求体不是有效的 JSON,你可能会看到类似以下的错误:
TypeError: Cannot read properties of undefined (reading 'body')
解决方案
要解决这些问题,你需要确保在应用中正确设置了中间件来解析 JSON 数据。在你的主文件(通常是 app.js
或 server.js
)中,添加以下中间件:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
// 使用中间件来解析 JSON 数据
app.use(express.json());
app.use('/', require('./routes/index'));
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
通过添加 app.use(express.json());
这一行,Express 将会自动解析传入的 JSON 数据,并将其作为 req.body
提供。
示例修复后的代码
现在,routes/index.js
文件可以正常工作了:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.json({ message: 'Hello World' });
});
router.post('/submit', (req, res) => {
console.log(req.body);
res.send('Data received');
});
module.exports = router;
通过正确设置中间件,你就可以在 routes
文件中正常使用 JSON 方法了。希望这能帮助你解决这个问题!
代码
你要看看是JSON报的错,还是req.hreaders 没有值,
找到问题了…routes里的名字只能是index.js…我改了some.js,在app.js把引用改了,正常使用,但就不能使用全局方法…晕…
把名字改回index.js正常了…
看来express要深度自定制了…
你用的express的多少版本,是用的express 自己的路由机制?我看不太懂你的意思