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

posted @ 2022-04-11 22:49  阿布_alone  阅读(3789)  评论(0编辑  收藏  举报
TOP