This post is about setting up XHRs on a local node script. There are two mainstream libraries to use.
Request
https://github.com/request/request
npm install request
Gotchas
- The standard
on
syntax actually doesn't return the body of the response, so you need to use the callback version if you want to parse and use the content.
TLDR
var request = require('request');
var options = {
url: 'https://api.github.com/repos/request/request',
headers: {
'User-Agent': 'request'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info.stargazers_count + " Stars");
console.log(info.forks_count + " Forks");
}
}
request(options, callback);
Fetch
https://www.npmjs.com/package/node-fetch
npm install node-fetch
Gotchas
-
whatwg-fetch
is a browser polyfill only, NOT usable innode.js
. For a server sidenode.js
application or anode
script, usenode-fetch
instead.
Usage
function checkRequest(req, res) {
var url = makeUrl(req);
req.url = url;
return fetch(url, req)
.then( (response) => {
console.log("Got: " + response.status);
console.log("Expected: " + res.code);
console.log(response.status == res.code);
return response.json();
})
.then( (json) => {
// do stuff with the body
});
}
async function runTests() {
while (input.length > 0) {
await checkNextRequest();
}
}
function checkNextRequest() {
var sample = input.shift();
return checkRequest(sample.request, sample.response);
}
Async and Await
There are a lot of ways in which async and await do NOT work. But async and await work with ES6. The simplest way to get it to work:
Install babel dependencies:
"dependencies": {
"node-fetch": "^1.7.1"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2017": "^6.24.1"
}
Run with command:
./node_modules/.bin/babel-node index.js
网友评论