After koa2 sets cors to a specific url, the frontend ajax cannot cross the domain after customizing the header. If the header is removed, it can cross the domain.

app.js

</span>

No "Access-Control-Allow-Origin" headerAccess-Control-Allow-Headers

// 
axios.post(`http://localhost:8089/api/test`, null)
        .then(response => {
            console.log(response.data);
        });

find a solution

Mar.18,2021

that's because all your code 1, including the options request browser, will pre-check before the non-simple request, and you haven't processed it, so you won't send the post request


directly.

A solution has been found
the options request needs to be processed

router.options('/api/test/', (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , myheader');
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    ctx.status = 200;
    return;
});

as for the problem of cross-domain without setting the request header, the reason is that my current cross-domain request is a simple request and does not send an options, in advance, so the cross-domain is still successful.

Menu