nodejs請求庫request(一)


一、request以及request-promise簡單介紹

  request以及request-promise是服務端發起請求的工具包。下面是一些基本用法(2種用法類似)

1、默認get請求

var request = require('request');


//1.  ----------------------簡單的get請求---------------------------
request('http://httpbin.org/get?a=b&c=d', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body) // 請求成功的處理邏輯,注意body是json字符串
    }
});

  結果:

{
  "args": {
    "a": "b",
    "c": "d"
  },                                                             
  "headers": {                                                   
    "Host": "httpbin.org",                                       
    "X-Amzn-Trace-Id": "Root=1-62544156-59e7be4155127c280000d4ee"
  },
  "origin": "183.8.148.251",
  "url": "http://httpbin.org/get?a=b&c=d"
}

  也可以這樣

request.get({
        url: "http://httpbin.org/get",
        params: {a: "aaa", b: "bbbbbbbb"}
    },
    function (error, response, body) {
        if (!error){
            //response是響應體,body是請求體數據,類似於python中res的text
            // console.log(response)
            console.log(body)

        }


    })

  結果:

{
  "args": {},
  "headers": {
    "Host": "httpbin.org",
    "X-Amzn-Trace-Id": "Root=1-625442b8-3a52b2c60f9cce4864774ef9"
  },
  "origin": "183.8.148.251",
  "url": "http://httpbin.org/get"
}

2、post請求

var request = require('request');
var url = "http://httpbin.org/post";
var requestData = {a: "a", b: 1, c: 3, d: 4};
request({
    url: url,
    method: "POST",
    json: true,
    headers: {
        "content-type": "application/json",
    },
    body: JSON.stringify(requestData)
}, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body) // 請求成功的處理邏輯
    }
});

  結果:

{
  args: {},
  data: '"{\\"a\\":\\"a\\",\\"b\\":1,\\"c\\":3,\\"d\\":4}"',
  files: {},
  form: {},
  headers: {
    Accept: 'application/json',
    'Content-Length': '39',
    'Content-Type': 'application/json',
    Host: 'httpbin.org',
    'X-Amzn-Trace-Id': 'Root=1-62544376-4c58082071bed1b70038ba85'
  },
  json: '{"a":"a","b":1,"c":3,"d":4}',
  origin: '183.8.148.251',
  url: 'http://httpbin.org/post'
}

  也可以這樣:

request.post({
    url:"http://httpbin.org/post",
    json: true,
    headers: {
        "content-type": "application/json",
    },

    body:JSON.stringify({a:1111,b:222222})
},function (err,res,data) {
    if(!err){
        console.log(data)
    }

})

  結果:

{
  args: {},
  data: '"{\\"a\\":1111,\\"b\\":222222}"',
  files: {},
  form: {},
  headers: {                              
    Accept: 'application/json',
    'Content-Length': '27',
    'Content-Type': 'application/json',
    Host: 'httpbin.org',
  },
  json: '{"a":1111,"b":222222}',
  origin: '183.8.148.251',
  url: 'http://httpbin.org/post'
}

 3、POST form格式上傳數據

request.post({
        url: 'http://httpbin.org/post',
        form: {key: 'value'}
    },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body) // 請求成功的處理邏輯
        }
    })

  結果:

{                                                        
  "args": {},
  "data": "",
  "files": {},                                           
  "form": {
    "key": "value"
  },
  "headers": {
    "Content-Length": "9",
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org",
    "X-Amzn-Trace-Id": "Root=1-62544574-2986a26310c89ab516ad98d4"
  },
  "json": null,
  "origin": "183.8.148.251",
  "url": "http://httpbin.org/post"
}

 

二.替代方案

  Request 在 2020.2.11 就被廢棄了, 幾乎接觸過Node的人都接觸過Request, 通過看到一個個庫的廢棄, 停止支持以及轉手, 我們可以看到開源事業的艱辛。

推薦一:替代庫got

  當然, 既然Request廢棄了, 我們也得繼續找個靠譜的請求庫啦。那就是got

1、性能對比

  下圖是官方文檔中將 got 與 requestnode-fetchkyaxiossuperagent這幾個常用的HTTP請求庫功能上的對比, 可以看到got的功能還算全面, 雖然不支持瀏覽器端使用。整體來說,還算不錯。

2、從 Request 遷移

  你可能覺得遷移會很麻煩, 但是並不是。讓我們從Request的文檔中拿出第一個例子

const request = require('request');

request('https://google.com', (error, response, body) => {
    console.log('error:', error);
    console.log('statusCode:', response && response.statusCode);
    console.log('body:', body);
});


// got
const got = require('got');

(async () => {
    try {
        const response = await got('https://google.com');
        console.log('statusCode:', response.statusCode);
        console.log('body:', response.body);
    } catch (error) {
        console.log('error:', error);
    }
})();

3、具體用法看官方文檔,這里截取一些

  重大變化

  • json 選項不是boolean類型, 而是 Object類型. 他將被序列化並當作body使用.
  • form 選項是 Object類型. 他可以是一個普通對象或者一個form-data 實例.
  • 沒有 oauth/hawk/aws/httpSignature 選項. 標記請求, 你需要創建一個自定義實例.
  • 沒有 agentClass/agentOptions/pool 選項.
  • 沒有 forever 選項. 你需要使用forever-agent.
  • 沒有proxy 選項. 你需要使用pass a custom agent.
  • 沒有 auth 選項. 你需要使用 username / password 代替.
  • 沒有 baseUrl 選項. 使用 prefixUrl代替, 如果不存在就用斜杠代替. 除非URL是一個實例, 否則它將始終是前置.
  • 沒有 removeRefererHeader 選項. 你可以移除 referer 頭 在beforeRequest 鈎子里:
const gotInstance = got.extend({
    hooks: {
        beforeRequest: [
            options => {
                delete options.headers.referer;
            }
        ]
    }
});

gotInstance(url, options);

沒有 jsonReviver/jsonReplacer選項, 但是你可以使用鈎子來解決:

const gotInstance = got.extend({
    hooks: {
        init: [
            options => {
                if (options.jsonReplacer && options.json) {
                    options.body = JSON.stringify(options.json, options.jsonReplacer);
                    delete options.json;
                }
            }
        ],
        beforeRequest: [
            options => {
                if (options.responseType === 'json' && options.jsonReviver) {
                    options.responseType = 'text';
                    options.customJsonResponse = true;
                }
            }
        ],
        afterResponse: [
            response => {
                const {options} = response.request;
                if (options.jsonReviver && options.customJsonResponse) {
                    response.body = JSON.parse(response.body, options.jsonReviver);
                }

                return response;
            }
        ]
    }
});

gotInstance(url, options);

 鈎子是非常有用的, 不是嗎? 查看更多 看看鈎子還能實現什么.

  關於流的更多信息

  讓我們快速看下 Request 的文檔中的另一個示例:

http.createServer((request, response) => {
    if (request.url === '/doodle.png') {
        request.pipe(request('https://example.com/doodle.png')).pipe(response);
    }
});

  很酷的功能是, Request 可以代理請求頭和流, 當然Got也能做到:

const stream = require('stream');
const {promisify} = require('util');
const got = require('got');

const pipeline = promisify(stream.pipeline);

http.createServer(async (request, response) => {
    if (request.url === '/doodle.png') {
        // 當有人向我們的服務器發出請求時,我們會收到一個body和一些請求頭.
        // 這些被傳遞給Got. 代理將會將數據下載到我們服務器,
        // 所以你不必使用`response.writeHead(statusCode, headers)` 和 `response.end(body)`.
        // 這些將自動完成.
        await pipeline(
            got.stream('https://example.com/doodle.png'),
            response
        );
    }
});

  一切都沒有真正改變. 只是記得使用 got.stream(url, options) 或者 got(url, {isStream: true, …}). 僅此而已!

  推薦二、替代庫Axios

    與瀏覽器端使用差不多,具體不多說

    推薦這2款,感覺還不錯。

 

轉自:https://www.cnblogs.com/goloving/p/13494617.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM