美文网首页
JS笔记:Request / Fetch

JS笔记:Request / Fetch

作者: 开水的杯子 | 来源:发表于2017-08-08 13:44 被阅读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

    • 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

    相关文章

      网友评论

          本文标题:JS笔记:Request / Fetch

          本文链接:https://www.haomeiwen.com/subject/mzgzlxtx.html