- Node.js发送请求,需要用到request这个模块
- request官网
导入
npm install request --save
import * as requestHttp from 'request';
get 请求
@Get('/xxxxx')
async getImage(@Req() request: Request, @Res() response: Response) {
const url = request.query.url;
requestHttp(url).pipe(response);
}
post 请求
post请求有3种方式,由请求头中的content-type决定,属于哪一种post请求
- application/x-www-form-urlencoded: 普通http请求方式,参数是普通的url参数拼接
- application/json: JSON请求方式,参数是json格式
- multipart/form-data: 文件上传
application/x-www-form-urlencoded
requestHttp.post(url).form(request.body).pipe(response);
或者
requestHttp({
method : 'post',
uri: url,
form: request.body
})
.pipe(response)
application/json
requestHttp({
method : 'post',
uri: url,
json: true,
headers: {
"content-type": "application/json",
},
body: request.body,
})
.pipe(response);
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:url, formData: formData}, function (error, response, body) {
if (!error && response.statusCode == 200) {
}
})
作者:袁峥
链接:https://www.jianshu.com/p/a156729ce499
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。