Reputation: 61
I'm currently trying to implement a patch request in my nodejs application. But I can't seem to get it to work. I have made sure my data structure is correct.
I've tried some different things like: returning my request.patch and promise but nothing seem to happen.
var request = require('request');
exports.patchOwner = function (options) {
var urlEncodedParams = encodeURI(options.nodeId);
request.patch(url + '/owner/owners/' + urlEncodedParams, JSON.stringify(options.body), function (err, res, body) {
//body is empty
});
}
Upvotes: 1
Views: 11659
Reputation: 2362
You can use Express for patch
request
server.js
app.patch("/data/:id/:patch", (q, r) => {
let id=q.params.id;
let id=q.params.patch;
//your logic
r.send({ res: "*PATCHED*" });
});
client.js
let ajax = (type, url, data, callback) => {
let xhr = new XMLHttpRequest();
xhr.open(/* GET */type, url, true/* ASYNC */);
xhr.onload = () => callback(xhr.status === 200 ? JSON.parse(xhr.response).res : xhr.status);
xhr.setRequestHeader('Content-Type', 'application/json');
if (type === "POST")
xhr.send(JSON.stringify(data));
else
xhr.send();//PUT - PATCH - DELETE - GET
}
usage
ajax('PATCH', '/data/1/something_to_patch', null, (res)=>{alert(res)});
same logic for GET
, PUT
and DELETE
.
but for POST
:
server.js
app.post("/data", (q, r) => {
let body_data = JSON.stringify(q.body);
r.send({ res: "*POST: " + body_data + "*" });
});
client; post data with js:
<script>
let data = {
"id": 1,
"name": "AJAX_POST"
}
ajax('POST', '/data', data, (res)=>{alert(res)});
</script>
client; post form:
<form action="/data" method="POST">
<input name="id" type="hidden" value="2" />
<input name="name" type="hidden" value="FORM_POST" />
<input type="submit" value="FORM_POST" />
</form>
Upvotes: -1
Reputation: 751
I would try something like this:
var fullUrl = url + '/owner/owners/' + encodeURI(options.nodeId);
var body = JSON.stringify(options.body);
request.patch({ url: fullUrl, body: body }, function (err, res, body) {
// do your thing
})
Upvotes: 0