nodejs 配置代理服务器

const express = require('express');
const proxy = require('http-proxy-middleware');
const cors = require('cors');
var app = express();


app.use(cors({
    credentials: true, 
    optionsSuccessStatus: 200,    
    origin: 'http://localhost:8080' // 设置为项目所在服务器目录(允许跨域请求的网址)
}));



app.use('/api', proxy({
    target:'http://192.168.31.65:8000/', // 服务器api地址目录
    changeOrigin: true,
    pathRewrite:{
        "^/api":""
    }
}));

app.listen(3000,'192.168.31.65', function(){ // 代理接口
    console.log('代理接口启动成功');
})

// 例如 api接口为 http://192.168.31.65:8000/api/getid/a
// 实际应该请求的地址为 http://192.168.31.65:3000/api/getid/a

https://www.cnblogs.com/litings/p/10575814.html

nodeJs环境添加代理

目的:实现前后端分离,前端减少路径请求的所需的路由文件;


第一步:安装http代理中间件

npm install http-proxy-middleware --save

第二步: express文件中(app.js)配置反向代理

// 1. 引入http-proxy-middleware模块
var proxy = require('http-proxy-middleware');

// 2. 代理中间件配置项
var options = {
    target: 'http://192.166.32.66:8080/', // target host
    changeOrigin: true, // needed for virtual hosted sites
};
// 3. 将请求路径按“代理中间件配置项”进行请求
app.use(proxy('/login/*',options));

解析:本地的请求地址是localhost:5000/login,当经过代理配置后,会将localhost:5000替换为http://192.166.32.66:8080/;所以实际的请求路径是http://192.166.32.66:8080/login;

 https://www.cnblogs.com/zero-zm/p/10014664.html

原文地址:https://www.cnblogs.com/LcxSummer/p/15137191.html