koa + Node.JS RESTful API 从本地传输到主机后Cors preflight origin error

Koa + Node.JS RESTful API Cors preflight origin error after transferring from local to host

我知道有很多关于 cors 预检错误的文章:

http://70.xx.xx.60/oms/api/login' from origin 'http://order.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow- Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

但是,我在本地环境中开发时遇到过这个问题,修复了它,当我将服务器移动到主机 (A2Hosting) 时,尽管按照他们的建议在 .htaccess 文件中启用了 cors,我已经返回到这个错误。以下是相关文件,如果有人可以查看并提供有关此问题在一次解决后再次弹出的原因的见解。我不想下载 chrome 插件解决方法,我想避免使用代理,我宁愿正确设置 cors 而忘记它。

我的server.js:

require("dotenv").config();
const Koa = require("koa");
const cors = require("@koa/cors");
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");
const baseRoutes = require("./routes");
const serve = require('koa-static');
const PORT = 30500;
const app = new Koa();

var options = {
    origin: '*',
    allowMethods: ['GET', 'POST', 'DELETE', 'PUT', 'OPTIONS', 'PATCH'],
    allowHeaders: '*',
    credentials: true
}

app.use(cors(options));
app.use(bodyParser());
app.use(baseRoutes.routes());
app.use(serve('./assets'));

app.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
});

我从前端调用(在这个例子中是 index.html 的登录页面)

async function postData(url = "", data = {}) {
    // Default options are marked with *
    return await fetch(url, {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, *cors, same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "omit", // include, *same-origin, omit
        headers: {
            "Content-Type": "application/json"
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: "follow", // manual, *follow, error
        referrerPolicy: "no-referrer", // no-referrer, *client
        body: JSON.stringify(data) // body data type must match "Content-Type" header
    });
}

如果您需要查看更多信息,请告诉我,我会提供。

我通过将 POST 请求 URL 从网站的 IP 版本更改为人类可读 URL 来解决此问题。我觉得自己很蠢,但我会把这个留给犯类似错误的其他人。