提问者:小点点

从本地传输到主机后,Koa+Node.js RESTful API Cors预执行源错误


我知道有很多关于cors飞行前错误的文章:

CORS策略已阻止http://70.xx.xx.60/oms/api/login“来自origin”http://order.example.com“:对预飞行请求的响应未通过访问控制检查:请求的资源上不存在”Access-Control-Allow-Origin“标头。 如果不透明响应满足您的需要,请将请求的模式设置为“no-cors”,以便在禁用CORS的情况下获取资源。

但是,当我在本地环境中进行开发时,我曾经遇到过这个问题,并修复了它,当我将服务器移动到主机(A2Host)时,尽管像他们推荐的那样在。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
    });
}

如果你需要看到更多的信息,请让我知道,我会提供它。


共1个答案

匿名用户

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