Example 1: node http request
const https = require('https')
const options = {
hostname: 'whatever.com',
port: 443,
path: '/todos',
method: 'GET'
}
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})
req.on('error', error => {
console.error(error)
})
req.end()
Example 2: node js request
const request = require('request');
request('http://www.google.com', function (error, response, body) {
console.error('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
});
Example 3: nodejs http get request to external server
const request = require("request");
const url = "<a href="https://my-json-server.typicode.com/edurekaDemo/noderequest/db">https://my-json-server.typicode.com/edurekaDemo/noderequest/db</a>";
request.get(url, (error, response, body) => {
let json = JSON.parse(body);
console.log(body);
});
Example 4: node send post request
const axios = require('axios')
axios
.post('https://whatever.com/todos', {
todo: 'Buy the milk'
})
.then(res => {
console.log(`statusCode: ${res.statusCode}`)
console.log(res)
})
.catch(error => {
console.error(error)
})
Example 5: node js do request
let request = require('request')
const formData = {
my_field: 'my_value',
my_buffer: Buffer.from([1, 2, 3]),
my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
attachments: [
fs.createReadStream(__dirname + '/attachment1.jpg'),
fs.createReadStream(__dirname + '/attachment2.jpg')
],
custom_file: {
value: fs.createReadStream('/dev/urandom'),
options: {
filename: 'topsecret.jpg',
contentType: 'image/jpeg'
}
}
};
request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});