node.js 在 Express.js 中使用 PUT 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18601922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using the PUT method with Express.js
提问by Brandon
I'm trying to implement update functionality to an Express.js app, and I'd like to use a PUT request to send the new data, but I keep getting errors using PUT. From everything I've read, it's just a matter of using app.put, but that isn't working. I've got the following in my routes file:
我正在尝试为 Express.js 应用程序实现更新功能,并且我想使用 PUT 请求来发送新数据,但我一直在使用 PUT 时遇到错误。从我读过的所有内容来看,这只是使用 app.put 的问题,但这不起作用。我的路由文件中有以下内容:
send = function(req, res) {
req.send(res.locals.content);
};
app.put('/api/:company', function(res,req) {
res.send('this is an update');
}, send);
When I use postman to make a PUT request, I get a "cannot PUT /api/petshop" as an error. I don't understand why I can't PUT, or what's going wrong.
当我使用邮递员发出 PUT 请求时,我收到“无法 PUT /api/petshop”作为错误消息。我不明白为什么我不能 PUT,或者出了什么问题。
采纳答案by headwinds
You may be lacking the actual update function. You have the put path returning the result back to the client but missing the part when you tell the database to update the data.
您可能缺少实际的更新功能。您有将结果返回给客户端的放置路径,但在您告诉数据库更新数据时丢失了该部分。
If you're using mongodb and express, you could write something like:
如果您使用 mongodb 和 express,您可以编写如下内容:
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);
}
});
This mean stack projectmay help you as it covers this CRUD functionality which I just used here swapping their articles for your companies. same same.
这意味着堆栈项目可能会帮助你,因为它涵盖了这个 CRUD 功能,我刚刚在这里使用它为你的公司交换他们的文章。彼此彼此。
回答by yaya
Also if you want to redirect in putor delete(to getadress), you can't use normal res.redirect('/path'), you should use res.redirect(303, '/path')instead. (source)
此外,如果你想重定向put或delete(get地址),你不能使用 normal res.redirect('/path'),你应该使用res.redirect(303, '/path')。(来源)
If not, you'll get Cannot PUTerror.
如果没有,你会得到Cannot PUT错误。
回答by jet street
change the order of callback function(req, res). not use function(res, req).
改变回调函数的顺序(req, res)。不使用函数(res,req)。
回答by selvaraj
Have you been checking out your headers information?
Because header should be header['content-type'] = 'application/json';then only you will get the update object in server side (node-express), otherwise if you have content type plain 'text/htm' like that you will get empty req.bodyin your node app.
你有没有检查过你的标题信息?因为标头应该是header['content-type'] = 'application/json';那么只有您才能在服务器端(node-express)中获得更新对象,否则如果您的内容类型为纯“text/htm”,您将empty req.body在您的节点应用程序中获得。

