我有一个API,如果我需要更新对象,我应该发送PATCH请求;问题是当我发送PATCH请求时,身体总是未定义的。
这是我如何发送PATCH请求Ex。
app.patch('/applications/update/:application_id', function(request, response) {
var application_id = request.params.application_id;
require('../../models/applications/update_application_by_id').get(request.body, application_id, function(result){
response.render('applications/details', {application_details:result});
});
});
<form enctype="application/json" class="form-horizontal" role="form" method="post" action="/applications/update/{{application_details._id}}">
<input type="hidden" name="_method" value="PATCH" />
<input type="text" name="name" class="form-control">
<button type="submit" class="btn btn-yellow pull-right">update</button>
</form>
这就是我如何处理它
exports.get = function(request_body, application_id, call_back){
var http_request = unirest("patch", "https://xx/api/applications/"+application_id);
http_request.headers({
"cache-control": "no-cache",
"content-type": "application/json",
"x-application-key": "xxxxxxxxxxxxxxxxxx"
});
http_request.type("json");
http_request.send(request_body);
http_request.end(function (http_response) {
console.log(http_request.body);
if (http_response.error) throw new Error(http_response.error);
return call_back(http_response.body);
});
}
答案 0 :(得分:1)
所以我们走了,
我通过非常简单的方式解决问题,因为我正在与API交谈所以我有模型文件与API交谈,所以我在这些文件上定义了我的方法,并将所有表单作为帖子并传递帖子正文作为模型的参数。
该示例将解释更多。
模型文件:
var request = require("request");
exports.get = function(request_body, application_id, call_back){
var options = {
method: 'PATCH',
url: 'http://XXXXXXXXXXXXXXXX'+ application_id,
headers:
{
'content-type': 'application/json',
'x-application-key': 'XXXXXXXXXXXXXXXXXXX'
},
body: request_body,
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
return call_back(body);
});
};
控制器文件:
app.post('/applications/update/:application_id', function(request, response) {
require('../../models/XXX/XXXX').get(request.body, request.params.application_id, function(result){
response.render('XXXXX/details', {response_update:result});
});
});
表格模板:
<form class="form-horizontal" role="form" method="post" action="/applications/update/{{application.[0]._id}}">
<div class="form-group">
<div class="col-sm-4">
<input type="text" name="name" class="form-control" value="{{application.[0].name}}" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-4">
<button type="submit" class="btn btn-yellow pull-right">update</button>
</div>
</div>
</form>
答案 1 :(得分:0)
您必须自己解开请求。
您的表单实际上是发送正常的POST请求:
<form enctype="application/json" class="form-horizontal" role="form" method="post" action="/applications/update/{{application_details._id}}">
因此,您需要一个将该POST转换为PATCH / DELETE的路由或中间件,_method
是。
答案 2 :(得分:0)
你最好安装和app.use()中间件express / methodoverride:
https://github.com/expressjs/method-override/blob/master/README.md
非常标准的方法,但请注意它期望的实际字段名称。