文章目录
- vue项目打包,api设置为替换api
一、vue项目打包,api设置为替换api
那么调用接口的时候默认是本地调用,这个时候部署到node上的项目会自己调用自己的资源,那么是调用不到的
二、使用koa2的koa2-proxy-middleware功能进行代理操作
一定不要使用koa-bodyparser,那么请求转发只能转发请求get,post无效也可能会503
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const logger = require('koa-logger')
const fs = require("fs");
const path = require("path");
const proxy = require('koa2-proxy-middleware');
// error handler
onerror(app)
// middlewares
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(views(__dirname + '/views', {
extension: 'pug'
}))
const options = {
targets: {
'/api/(.*)': {
target: 'http://xx.xxx.xx.xx:80/',
ws: true,
changeOrigin: true,
pathRewrite: {
'^/api/': '' //和前端代理一样,选择api替换为什么
}
},
}
}
app.use(proxy(options));
// logger
app.use(async (ctx, next) => {
ctx.set("Access-Control-Allow-Origin", "*");
if (ctx.url == "/") {
await next();
} else {
const html = await fs.readFileSync(path.resolve(__dirname + "/public/index.html"));
ctx.body = html.toString();
}
})
// error-handling
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
});
module.exports = app