Reputation: 59
I am doing an assignment for https request in Node.js. The assignment requests that using the native https module for patching data. Also, the data we want to update can be input after the js file, like node xxx.js "update something". The question is when patching, the update is uploaded but the old data is not updated. So, it causes that the new and old data exist together. Thanks!
const https = require('https');
const args = process.argv;
const act = args[2];
const update = args[3]
const options = {
hostname: 'reqres.in',
port: 443,
path: `/api/users/${act}`,
method: 'PATCH',
headers: {
"Content-Type": 'application/x-www-form-urlencoded'
}
}
const req = https.request(options.options_patch, res => {
let data = '';
console.log('Status: ', res.statusCode)
console.log('Headers: ', JSON.stringify(res.headers))
res.setEncoding('utf8');
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
console.log('Body: ', JSON.parse(data));
})
}).on('error', e => {
console.error(e);
})
req.write(JSON.stringify(update));
req.end();
}
Upvotes: 0
Views: 2583
Reputation: 3894
const https = require('https');
const args = process.argv;
const act = args[2];
const update = args[3];
const options = {
hostname: 'reqres.in',
port: 443,
path: `/api/users/${act}`,
method: 'PATCH',
headers: {
"Content-Type": 'application/x-www-form-urlencoded'
}
}
const req = https.request(options, res => {
let data = '';
console.log('Status: ', res.statusCode);
console.log('Headers: ', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
console.log('Body: ', JSON.parse(data));
});
}).on('error', e => {
console.error(e);
});
req.write(update);
req.end();
node test.js path "data"
Status: 200 Headers: {"date":"Wed, 08 Jul 2020 12:59:16 GMT","content-type":"application/json; charset=utf-8","content-length":"50","connection":"close","set-cookie":["__cfduid=d76ab451f50acf77b2fe9da83cbff44521594213156; expires=Fri, 07-Aug-20 12:59:16 GMT; path=/; domain=.reqres.in; HttpOnly; SameSite=Lax; Secure"],"x-powered-by":"Express","access-control-allow-origin":"*","etag":"W/"32-PB4zlwTjg/gFA9Skv/cu8Rzo1N4"","via":"1.1 vegur","cf-cache-status":"DYNAMIC","cf-request-id":"03d01b5e6500000c1117955200000001","expect-ct":"max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"","server":"cloudflare","cf-ray":"5af9fb43d9af0c11-AMS"} Body: { data: '', updatedAt: '2020-07-08T12:59:16.501Z' }
FYI: This could also be done with curl
or wget
.
Upvotes: 1