写一个转发http 请求的方法可以支持 路径传参,body传参
时间: 2024-05-19 13:15:45 浏览: 13
可以使用 Node.js 中的 `http` 模块和 `request` 模块来实现一个支持路径传参和 body 传参的转发 HTTP 请求的方法。具体代码如下:
```javascript
const http = require('http');
const request = require('request');
function forwardHttpRequest(path, method, body, headers, targetUrl, callback) {
// 构造请求选项
const requestOptions = {
url: targetUrl + path,
method: method,
headers: headers,
body: body
};
// 发送请求
request(requestOptions, (error, response, responseBody) => {
if (error) {
// 请求出错
callback(error, null);
} else {
// 请求成功
callback(null, responseBody);
}
});
}
```
使用方法如下:
```javascript
const targetUrl = 'http://example.com';
// 路径传参
const path = '/users/123';
// Body 传参(JSON 格式)
const body = JSON.stringify({
name: 'John Doe',
email: 'john.doe@example.com'
});
// 请求头
const headers = {
'Content-Type': 'application/json'
};
// 发送 POST 请求
forwardHttpRequest(path, 'POST', body, headers, targetUrl, (error, responseBody) => {
if (error) {
console.error('请求出错:', error);
} else {
console.log('请求成功,响应结果为:', responseBody);
}
});
```
注意,上述代码中使用了 `request` 模块来发送 HTTP 请求,因此需要先安装该模块。可以使用以下命令进行安装:
```
npm install request
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)