JS笔记:Request / Fetch

2017-08-08  本文已影响35人  开水的杯子

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

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

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

上一篇 下一篇

猜你喜欢

热点阅读