nodejs使用request发送http请求

在nodejs的开发中,有时需要后台去调用其他服务器的接口,这个时候,就需要发送HTTP请求了。有一个简单的工具可以用,Simplified HTTP request client,可以比较方便的模拟请求。

安装
npm install --save request
1
使用
最简单的GET请求,用法如下:

var request = require('request');
request('http://www.baidu.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the baidu homepage.
  }
})
1
2
3
4
5
6
POST application/json
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) {
    }
}); 
1
2
3
4
5
6
7
8
9
10
11
12
POST application/x-www-form-urlencoded
request.post({url:'http://service.com/upload', form:{key:'value'}}, function(error, response, body) {
    if (!error && response.statusCode == 200) {
    }
})
1
2
3
4
POST multipart/form-data
var formData = {
    // Pass a simple key-value pair
    my_field: 'my_value',
    // Pass data via Buffers
    my_buffer: new Buffer([1, 2, 3]),
    // Pass data via Streams
    my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
};
request.post({url:'http://service.com/upload', formData: formData}, function (error, response, body) {  
    if (!error && response.statusCode == 200) {
    }
})
1
2
3
4
5
6
7
8
9
10
11
12
如上所示,formData可以直接放key-value格式的数据,也可以放buffer,或者是通过流描述的文件。

参考
github request

pass JSON to HTTP POST Request


转载:https://blog.csdn.net/dreamer2020/article/details/52074516 
 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值