我有一个API,如果我需要更新对象,我应该发送PATCH请求;问题是,当我发送PATCH请求时,主体始终是不确定的。
这就是我发送PATCH请求的方式。
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);
});
}
最佳答案
所以我们开始
我用非常简单的方法解决了这个问题,因为我正在使用API,所以我有与API一起使用的模型文件,因此我在这些文件上定义了我的方法,并将所有表单都作为post并将post body作为参数传递给了模型。
该示例将说明更多。
模型文件:
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>
关于html - NodeJS:如何使用html表单发送PATCH&DELETE请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38112722/