节点转发路径请求到另一台服务器

Node forward path request to another server

目前有一个网站 运行 一个处理所有请求的节点服务器 example.com 我在一个单独的服务器 (运行 apache) 上创建了一个完全独立的 wordpress 博客,我会就像在 172.23.23.23 IP 地址的 example.com/blog 这样的路径上服务。 wordpress 服务器不共享任何代码,甚至不知道除自身之外任何东西的存在

node/express 以这种方式转发所有请求的最佳方式是什么?另外,新 wordpress 服务器的 A/CNAME 记录应该指向什么?

这行得通:这是您需要放入节点应用程序的内容:

var express = require('express');
var app = module.exports = express();

var proxy = require('http-proxy').createProxyServer({
    host: 'http://your_blog.com',
    // port: 80
});
app.use('/blog', function(req, res, next) {
    proxy.web(req, res, {
        target: 'http://your_blog.com'
    }, next);
});

app.listen(80, function(){
    console.log('Listening!');
});

然后在您的 wordpress 应用程序中,您需要将站点 URL 设置为 http://your_node_app.com/blog

注意:您可能已经有了一个 Express 应用程序,可能 body-parser middleware which causes errors and generally doesn't play well with POST requests in http-proxy

你会在这些线程中找到几个解决方案,即 1:只需将此代理 放在 主体解析器之前,或 2:使用 connect-restreamer

工作和测试

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('*', createProxyMiddleware({target: 'https://yourdomain.com', changeOrigin: true}));
app.listen(3000);

先安装以下

npm i -s express
npm i -s http-proxy-middleware