express 如何 实现 发送https请求
时间: 2023-08-02 12:09:51 浏览: 44
要在 Express 中发送 HTTPS 请求,需要使用 Node.js 内置的 HTTPS 模块。
以下是一个示例代码,展示如何在 Express 应用程序中发送 HTTPS 请求:
```javascript
const https = require('https');
const express = require('express');
const app = express();
app.get('/', (req, res) => {
https.get('https://example.com', (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
res.send(data);
});
}).on('error', (error) => {
console.error(error);
});
});
app.listen(3000, () => console.log('Server started'));
```
在上面的示例中,我们使用 `https.get()` 方法发送 HTTPS 请求,并通过 `response` 对象接收响应数据。然后,我们将数据发送回客户端。
请注意,如果要发出 POST 请求,则需要使用 `https.request()` 方法,并将请求体作为参数传递。
```javascript
const https = require('https');
const express = require('express');
const app = express();
app.post('/', (req, res) => {
const data = JSON.stringify({
message: 'Hello, world!'
});
const options = {
hostname: 'example.com',
port: 443,
path: '/api',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
const request = https.request(options, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
res.send(data);
});
}).on('error', (error) => {
console.error(error);
});
request.write(data);
request.end();
});
app.listen(3000, () => console.log('Server started'));
```
在上面的示例中,我们使用 `https.request()` 方法发送 HTTPS POST 请求,并将请求体作为参数传递。我们还设置了请求头,以指定请求体的类型和长度。然后,我们将数据发送回客户端。