var express = require('express');
var app = express();
app.get('/products/productList/:id', (res, req) => {
console.log("product Id - " + req.params.id);
});
此代码有什么问题?我该怎么做才能避免以下错误
TypeError: Cannot read property 'id' of undefined
at app.get (E:\Projects\Craiglist\trial\app.js:46:46)
at Layer.handle [as handle_request] (E:\Projects\Craiglist\trial\node_modules\express\lib\router\layer.js:95:5)
at next (E:\Projects\Craiglist\trial\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (E:\Projects\Craiglist\trial\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\Projects\Craiglist\trial\node_modules\express\lib\router\layer.js:95:5)
at E:\Projects\Craiglist\trial\node_modules\express\lib\router\index.js:281:22
at param (E:\Projects\Craiglist\trial\node_modules\express\lib\router\index.js:354:14)
at param (E:\Projects\Craiglist\trial\node_modules\express\lib\router\index.js:365:14)
at Function.process_params (E:\Projects\Craiglist\trial\node_modules\express\lib\router\index.js:410:3)
at next (E:\Projects\Craiglist\trial\node_modules\express\lib\router\index.js:275:10)
答案 0 :(得分:3)
(res, req)
你改变了函数参数的顺序:)
请求是第一个参数,响应是第二个。
试试这个:
app.get('/products/productList/:id', (req, res) => {
console.log("product Id - " + req.params.id);
});
答案 1 :(得分:0)
确保您required
body-parser
。并使用bodyParser.urlencoded
。
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
这应该在您的.get
路线定义之前。
你必须在<{p>}之前做npm install body-parser