How is the front-end project configured using the koa 2 agent?

after the front end is developed in React, you want to try the front and back end separate deployment.
then uses koa2 and http-proxy-middleware to implement the proxy.

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...")
});
The

backend has received the request and returned data, however, the browser interface reported an error of 404

clipboard.png

:

clipboard.png

how can I improve it? Thank you!

Mar.02,2021

set ctx.respond = false


when setting header the request has been responded to the client


you can take a look at koa-server-http-proxy this library, the koa version of http-proxy-middleware.

Menu