【发布时间】:2021-07-14 20:36:45
【问题描述】:
我正在尝试编写一个类似于此处记录的函数 (Using the PUT method with Express.js),但失败了。
在本例中,我需要检索 :company 中的值 我得到的是undefined
我尝试了很多变化,包括
var company = req.company;
var company = JSON.stringify(req.company);
var company = req.company[0];
到目前为止,所有这些都产生了相同的结果。正确的语法是什么?
app.put('/api/:company', function (req, res) {
var company = req.company;
company = _.extend(company, req.body);
company.save(function(err) {
if (err) {
return res.send('/company', {
errors: err.errors,
company: company
});
} else {
res.jsonp(company);
}
});
更新: 根据@Robot的建议,我也试过了
var company = req.param.company
and
console.log(req.param)
第二个是我最接近的答案
[function param]
附加测试: 让 foo = req.param; 然后 富() 产量:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>TypeError: Cannot read property 'params' of undefined<br> at param (/home/w/node_modules/express/lib/request.js:236:21)<br> at app.put (/home/w/server.js:195:15)<br> at Layer.handle [as handle_request] (/home/w/node_modules/express/lib/router/layer.js:95:5)<br> at next (/home/w/node_modules/express/lib/router/route.js:137:13)<br> at Route.dispatch (/home/w/node_modules/express/lib/router/route.js:112:3)<br> at Layer.handle [as handle_request] (/home/w/node_modules/express/lib/router/layer.js:95:5)<br> at /home/w/node_modules/express/lib/router/index.js:281:22<br> at param (/home/w/node_modules/express/lib/router/index.js:354:14)<br> at param (/home/w/node_modules/express/lib/router/index.js:365:14)<br> at Function.process_params (/home/w/node_modules/express/lib/router/index.js:410:3)</pre>
</body>
</html>
修复: 感谢@AmIDeranged 和本教程https://www.robinwieruch.de/node-express-server-rest-api
你可以使用任何一个
req.params.company
或
${req.params.company}
我不确定 ${} 会在对话中添加什么内容,但要等到另一天(!!!)
【问题讨论】:
-
尝试 req.params.company - 而不是 req.param.company。
-
谢谢!!!我只是想说我在本教程的帮助下也修复了它robinwieruch.de/node-express-server-rest-api
标签: node.js express routes put