我是节点js的新手,在使用body-phraser时,我收到了错误: ReferenceError: status is not defined
。代码如下所示
当json发布到 localhost:3000 / 产品时,以下错误似乎正在上升,但我无法弄清楚为什么会发生这种情况。是否由于我的代码中的错误而发生引用错误:
我得到的错误是:
ReferenceError: status is not defined
at app.use (/home/marper96/Desktop/node/node-rest-shop/app.js:22:5)
at Layer.handle_error (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/layer.js:71:5)
at trim_prefix (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:315:13)
at /home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:335:12)
at next (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:275:10)
at Layer.handle_error (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/layer.js:67:12)
at trim_prefix (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:315:13)
at /home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/marper96/Desktop/node/node-rest-shop/node_modules/express/lib/router/index.js:335:12)
我使用的代码:
router.post('/',(req,res,next) =>{
const product ={
name :req.body.name,
price :req.body.price
};
res.status(201).json({
messsage:'Handelling post requests to /products',
createdproduct:product
});
});
module.exports =router;
答案 0 :(得分:0)
请将正文光标添加到路由器,如下面的行
const router = require("express").Router();
const bodyParser = require("body-parser");
router.use(bodyParser.json());
您必须使用'使用'将身体解析器添加到中间件。上面的方法和你的代码,
router.post('/',(req,res,next) =>{
const product ={
name :req.body.name,
price :req.body.price
};
res.status(201).json({
messsage:'Handelling post requests to /products',
createdproduct:product
});
});