JS笔记:Request / Fetch

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 in node.js. For a server side node.js application or a node script, use node-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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容