Search code examples
node.jscorskoa

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


I know there are a lot of articles out there regarding the cors preflight error:

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.

However, I had this issue once when I was developing in my local environment, fixed it, and when I moved my server to a host (A2Hosting), despite enabling cors in the .htaccess file like they recommend, I have returned to getting this error. The following are the relevant files if anyone could take a look and offer insight as to why this issue has popped up again after being resolved once. I am not looking to download the chrome plugin workaround, and I would like to avoid a proxy, I'd prefer to just setup cors correctly and forget about it.

my 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}`);
});

my call from the frontend (in this example the login page at 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
    });
}

If you need to see more info, please let me know and I will provide it.


Solution

  • I resolved this by changing the POST request URL from the IP version of the website to the human readable URL. I feel dumb, but I will leave this up for other people who make a similar mistake.