Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

nodejs访问两个不同的路由,如何设置一个路由使用代理,一个路由不使用代理?

1、希望http://localhost:3000/使用代理变成http://localhost:59125访问根目录下的文件
2、访问http://localhost:3000/bulid不使用代理,直接加载根目录下问题

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const router = express.Router();
let buildRouter = require('./router/build.js');
let options = {
    // 代理跨域目标接口
 target: 'http://localhost:59125',
 changeOrigin: true,
 // 修改响应头信息,实现跨域并允许带cookie
 onProxyRes: function(proxyRes, req, res) {
        res.header('Access-Control-Allow-Origin', '*');
 }
    // 修改响应信息中的cookie域名
//  cookieDomainRewrite: ''  // 可以为false,表示不修改
}
var exampleProxy = createProxyMiddleware(options); //开启代理功能,并加载配置
app.use('/build2020', buildRouter);
app.use('/', exampleProxy);
app.use(express.static('./public'));
app.listen(3000, function(){ // 代理接口
 console.log('代理接口启动成功');
})
// 例如 api接口为 http://192.168.31.65:8000/api/getid/a
// 实际应该请求的地址为 http://192.168.31.65:3000/api/getid/a
var express = require('express');
let router = express.Router();
router.post('/', (req, res, next)=>{
    next();
});
module.exports = router;

无法打开路由


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

每个服务只做一件事,看样子你应该是启动了两个业务服务开在59125端口和3000端口,那就用nginx做个代理吧,统一访问第三个端口,比如80(或者8080),让nginx做转发。

server{
    linsten: 80;
    
    location /{
        proxy_pass http://127.0.0.1:59125
    }
    
    location /build/{
        proxy_pass http://127.0.0.1:3000
    }
}

这样就直接访问 localhost就行了,不用带端口号。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...