查看: 22|回覆: 0

Node.js之request模块 发送请求

[複製鏈接]

5

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2011-11-9
發表於 2020-9-9 17:15:00 | 顯示全部樓層 |閲讀模式
  • 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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 



来源:https://www.cnblogs.com/jcz1206/p/13640039.html
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部