nodejs和nginx都可以反向代理,解決跨域問題。
本地服務
const express = require('express')
const app = express()
//如果它在最前面,後面的/開頭的都會被攔截
app.get('/', (req, res) => res.send('Hello World!'))
app.use(express.static('public'));//靜態資源
app.use('/dist', express.static(path.join(__dirname, 'public')));//靜態資源
//404
app.use('/test', function (req, res, next) {
res.status(404).send("Sorry can't find that!");
});
app.use(function (req, res, next) {
//TODO 中間件,每個請求都會經過
next();
});
app.use(function (err, req, res, next) {
//TODO 失敗中間件,請求錯誤後都會經過
console.error(err.stack);
res.status(500).send('Something broke!');
next();
});
app.listen(4000, () => console.log('Example app listening on port 4000!'))
與request配合使用
這樣就將其它服務器的請求代理過來了
const request = require('request');
app.use('/base/', function (req, res) {
let url = 'http://localhost:3000/base' + req.url;
req.pipe(request(url)).pipe(res);
});
使用http-proxy-middleware
const http_proxy = require('http-proxy-middleware');
const proxy = {
'/tarsier-dcv/': {
target: 'http://192.168.1.190:1661'
},
'/base/': {
target: 'http://localhost:8088',
pathRewrite: {'^/base': '/debug/base'}
}
};
for (let key in proxy) {
app.use(key, http_proxy(proxy[key]));
}
監聽本地文件變化
使用nodemon插件。--watch test
指監聽根目錄下test文件夾的所有文件,有變化就會重啓服務。
"scripts": {
"server": "nodemon --watch build --watch test src/server.js"
}