前端用React开发完成后,想试着前后端分离部署。
于是用了koa2和http-proxy-middleware想实现代理。
const Koa = require('koa')
const path = require('path')
const proxy = require('http-proxy-middleware')
const static = require('koa-static')
const fs = require('fs')
const app = new Koa()
app.use(async (ctx, next) => {
if(ctx.url.startsWith('/v1')) {
return proxy({
target: 'http://localhost:8080', // 服务器地址
changeOrigin: true,
secure: false,
pathRewrite: {
'^/v1' : '/mobile/v1'
}
})(ctx.req, ctx.res, next)
}
return next()
})
app.use(static(path.join(__dirname, './project/build')))
app.use(async (ctx) => {
ctx.body = fs.readFile('./project/build/index.html')
})
app.listen(3000, () => {
console.log('Listening 3000...')
});
后端已经收到了该请求并返回了数据,然而,在浏览器该接口却报错404
后台环境也报错:
请问如何改进?谢谢!
在proxy前面设置
ctx.respond = false