【问题标题】:How do I retrieve the route in app.put()?如何在 app.put() 中检索路由?
【发布时间】: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 &#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}

我不确定 ${} 会在对话中添加什么内容,但要等到另一天(!!!)

【问题讨论】:

标签: node.js express routes put


【解决方案1】:

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

你可以使用任何一个

req.params.company

${req.params.company}

【讨论】:

    【解决方案2】:
    app.put('/api/:company', handler);
    

    /api/abcCompanyreq.param.company发送请求将返回abcCompany

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

    您可以访问req.param.company中的公司数据

    【讨论】:

    • 感谢您的回复。我还是有问题。由于路由(表示为:company)是一个字符串,我试图使用console.log(company)=> undefined和console.log(req.params)=> [Function:param]打印它。我误会了什么?
    猜你喜欢
    • 1970-01-01
    • 2019-07-20
    • 2023-01-31
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多