前端使用代理
react中
在src目录下新建文件setupProxy.js
const {createProxyMiddleware} = require('http-proxy-middleware')
//代理设置
module.exports = function (app) {
app.use(createProxyMiddleware("/api", {
target: 'http://localhost:3300',
secure: false,
changeOrigin: true,
pathRewrite: {
"^/api": "/test"
}
}));
}
vue项目中
在config/index.js的dev节点下新增代理信息
//设置代理
proxyTable: {
'/api': {
target: 'http://localhost:3300',
secure: false,
changeOrigin: true,
pathRewrite: {
"^/api": "/test"
}
}
}
建立专门的代理项目(egg项目举例)
config.js
const host = 'http://test.tms.loji.com';
//公共头部
var commonHeaders = {
'content-type': 'application/json',
Cookie: '登录之后cookie'
};
module.exports = {
host,
commonHeaders
}
home.js
'use strict';
const Controller = require('egg').Controller;
const {host, commonHeaders} = require('../../config');
class HomeController extends Controller {
getHeaderAndData(ctx){
let data = ctx.request.body;
let contentType = ctx.headers['content-type'];
let headers = JSON.parse(JSON.stringify(commonHeaders));
if(!/json/.test(contentType)){
headers['content-type'] = contentType;
}else{
data = JSON.stringify(data);
}
return {data, headers}
}
//匹配所有路由(作为代理处理)
async allRoute(){
const {ctx} = this;
const {data = null, headers} = this.getHeaderAndData(ctx);
let response = await ctx.curl(host + ctx.originalUrl, {
method: ctx.method,
data,
headers
});
try{
ctx.body = JSON.parse(response.data);
}catch(e){
console.error('解析json失败!!!', response);
ctx.body = {
status: 0,
msg: '解析json错误'
}
}
}
}
module.exports = HomeController;
route.js
'use strict';
module.exports = app => {
const { router, controller } = app;
router.all('*', controller.home.allRoute);
};
egg配置(与代理无关)
'use strict';
const path = require('path');
module.exports = appInfo => {
const config = exports = {};
//跨域允许
config.cors = {
origin: '*',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
};
//使用ejs模板
config.view = {
mapping: {
'.html': 'ejs',
},
};
//禁止表单报错
config.security = {
csrf: {
enable: false,
},
};
//规定静态资源路劲
config.static = {
prefix:'/',
dir: [path.join(appInfo.baseDir, 'app/public')]
}
//设置系统加密串
config.keys = appInfo.name + '_1592967337826_1169';
//使用的中间件
config.middleware = [];
//自定义配置
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};