https http proxy

165 阅读3分钟

express启动https服务,用来作为html页面的路由服务。 //server.js文件

const express = require('express'); 
const { createProxyMiddleware } = require('http-proxy-middleware'); 
const https = require('https') 
const app = express(); 
const server = https.createHttpServe(option,app) // 配置代理服务器 
app.use('/api', createProxyMiddleware({ 
    target: 'http://119.23.45.56:8080', //本地后端接口服务 
    changeOrigin: true, 
    pathRewrite: {
        '^/api': '', // 可选,如果您的远程服务器不需要 /api 前缀 
    }, 
})); // 其他路由和中间件配置 
app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); // 启动服务器 server.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });

// index.html文件

<script> 
    fetch('/api/getuser', { 
        method: 'post', 
        headers: { // 您的请求头 }
    }) 
    .then(response => response.json()) 
    .then(data => console.log(data)) 
    .catch(error => console.error('Error:', error)); 
</script> 

通过node server.js命令启动项目后 会访问biddata.com/index 然后访问的是index.html ,index.html页面会发向本地后端服务的接口访问,在index.html中通过fetch('/api/getuser')发起本地接口服务请求,由于页面是https的,后端接口是http的,会报错,所以通过在server.js文件中通过http-proxy-middleweare 设置如下app.use('/api', createProxyMiddleware({ target: 'http://119.23.45.56:8080', //本地后端接口服务 changeOrigin: true, pathRewrite: { '^/api': '', // 可选,如果您的远程服务器不需要 /api 前缀 }, }));,可以成功访问接口,请求到数据。现在要在本地访问部署到服务器上的后端服务 backend.com.cn/,服务器上的服务本地访… 109.68.22.55:8080 ,我想要在本地成功访问部署在服务器上的后端服务,应该如何解决


为了在本地成功访问部署在服务器上的后端服务,且考虑到后端服务是通过 HTTP 提供的,而您的前端是通过 HTTPS 提供的,您可以使用相似的代理设置。但由于您需要通过一个特定的代理服务器访问远程后端服务,这就涉及到了一个额外的代理层。以下是解决这个问题的步骤:

1. 配置代理以通过特定代理服务器转发

您可以在 http-proxy-middleware 的配置中添加一个 agent 选项,以指定用于代理请求的 HTTP/HTTPS 代理服务器。这样,所有到 /api 路径的请求都会通过您指定的代理服务器转发。

首先,安装 http-proxy-agenthttps-proxy-agent(根据您的代理服务器是 HTTP 还是 HTTPS):

npm install http-proxy-agent

2. 更新 server.js 文件

server.js 中配置代理,使其通过指定的代理服务器转发请求:

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const HttpProxyAgent = require('http-proxy-agent'); // 或 'https-proxy-agent'
const https = require('https');

const app = express();
const options = {
  // ...您的 HTTPS 服务器选项
};
const server = https.createServer(options, app);

// 代理服务器配置
const proxyAgent = new HttpProxyAgent('http://109.68.22.55:8080'); // 代理服务器的地址

app.use('/api', createProxyMiddleware({
    target: 'http://backend.com.cn', // 远程后端服务
    changeOrigin: true,
    pathRewrite: { '^/api': '' },
    agent: proxyAgent,
}));

// 其他路由和中间件配置
// ...

server.listen(3000, () => {
    console.log('Server is running on https://localhost:3000');
});

3. 测试代理配置

启动您的 Express 应用,并尝试通过前端页面访问 /api 路径。应该可以看到请求被成功转发到您的远程后端服务,且经过指定的代理服务器。

注意事项

  • 确保代理服务器允许您的请求,并且配置正确。
  • 如果您的代理服务器使用的是 HTTPS,您需要使用 https-proxy-agent 而不是 http-proxy-agent
  • 测试这种配置时,请仔细检查网络请求,确保请求正确

路由到您的代理服务器并且最终到达远程后端服务。

  • 如果您的代理服务器要求身份验证,您可能需要在代理配置中添加相关的认证信息。
  • 由于您正在设置一个中间件来代理请求,确保这个中间件的配置不会与您应用中的其他路由或中间件冲突。

使用这种方法,您应该能够在本地通过 HTTPS 安全地访问部署在远程 HTTP 服务器上的后端服务,而无需担心 HTTPS 和 HTTP 之间的混合内容问题。