如何在 app.put() 中检索路线?

How do I retrieve the route in app.put()?

我正在尝试编写一个类似于此处记录的函数 (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 &#39;params&#39; of undefined<br> &nbsp; &nbsp;at param (/home/w/node_modules/express/lib/request.js:236:21)<br> &nbsp; &nbsp;at app.put (/home/w/server.js:195:15)<br> &nbsp; &nbsp;at Layer.handle [as handle_request] (/home/w/node_modules/express/lib/router/layer.js:95:5)<br> &nbsp; &nbsp;at next (/home/w/node_modules/express/lib/router/route.js:137:13)<br> &nbsp; &nbsp;at Route.dispatch (/home/w/node_modules/express/lib/router/route.js:112:3)<br> &nbsp; &nbsp;at Layer.handle [as handle_request] (/home/w/node_modules/express/lib/router/layer.js:95:5)<br> &nbsp; &nbsp;at /home/w/node_modules/express/lib/router/index.js:281:22<br> &nbsp; &nbsp;at param (/home/w/node_modules/express/lib/router/index.js:354:14)<br> &nbsp; &nbsp;at param (/home/w/node_modules/express/lib/router/index.js:365:14)<br> &nbsp; &nbsp;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}

我不确定 ${} 添加到对话中的内容,但这留给了另一天(!!!)

app.put('/api/:company', handler);

/api/abcCompany 发送请求,req.param.company 将 return abcCompany

注意将在 req.company 中,除非您编写自己的中间件可以填充 req.company 以将其传递给其他中间件

您可以访问 req.param.company

中的公司数据

感谢@AmIDeranged 和本教程https://www.robinwieruch.de/node-express-server-rest-api

你可以使用任何一种

req.params.company

${req.params.company}