37
loading...
This website collects cookies to deliver better user experience
json()
, but still, it's an extra step. Currently, the module supports HTTP by default and needs to be required for https, so const http = require('http');
or const https=require('https');
.const https = require('https');
const options = {
hostname: 'jsonplaceholder.typicode.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);
});
node-fetch
is a lightweight module that enables us to use fetch()
in Node. The package is very similar to window.fetch()
in native JavaScript, but has a few differences (see node-fetch docs).mkdir node-api-fetch
npm init -y
to be able to install node packages.cd node-api-fetch
npm init -y
node-fetch
to make fetch requests.npm install node-fetch
index.js
file.touch index.js
// import node-fetch
const fetch = require('node-fetch');
// set url as constant
const URL = 'https://jsonplaceholder.typicode.com/todos';
fetch(URL)
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.error(err));
res.body
in node-fetch
is a readable stream, so decoding can be handled independently, which is very convenient. The downside is that it only supports res.text()
, res.json()
, res.blob()
, res.arraybuffer()
, and res.buffer()
. There is no caching built-in and no server-side cookie store, so Set-Cookie
headers have to extracted manually.mkdir node-api-axios
npm init -y
to be able to install node packages.cd node-api-axios
npm init -y
axios
to make fetch requests.npm install axios
index.js
file.touch index.js
// import node-fetch
const axios = require('axios');
// set url as constant
const URL = 'https://jsonplaceholder.typicode.com/todos';
axios
.get(URL)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
http