Home > OS >  Shopify - CORS error when making fetch request to NodeJs Express server || No 'Access-Control
Shopify - CORS error when making fetch request to NodeJs Express server || No 'Access-Control

Time:06-01

I'm currently building a tracking software for e-commerce brands.

I want to provide a JS script that Shopify store owners can add to their post-purchase order status page so that I can track the purchases.

When a customer orders something and lands on the order status page I want to send a request to my node.js express server to indicate someone placed an order. My problem is when making that request I get this error:

Access to fetch at 'http://localhost:8080/xxx from origin 'http://127.xxxxx' has been blocked by CORS policy: 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.

My code

This is my server code:

const PORT = process.env.SERVER_PORT || 8080;
const app = express();

app.use(express.json());
const corsOptions = {
    origin: 'http://127.xxxx',
    credentials: true, // access-control-allow-credentials:true
    optionSuccessStatus: 200,
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    allowedHeaders: "Origin, Content-Type, Accept",
}
app.use(cors(corsOptions));
app.use("/route1", route1);

app.listen(PORT, () => {
    console.log("Now listening on port "   PORT);
});

And this is the code on the post-purchase order status page on the shopify store:

fetch("http://localhost:8080/xxx", {
    method: "PATCH",
    body: bodyData,
    headers: {
        'Content-type': 'application/json; charset=UTF-8',
    }
}). then((response) => response.json()).then((json) => console.log(json));

What I know and checked

I know since it is a PATCH request there is also a preflight request. And when I check out the preflight request in the browser console the header has the correct Access-Control-Allow-Origin but the actual PATCH request does not even have the Access-Control-Allow-Origin header at all.

I honestly do not know where to go from here and have been stuck with this problem for a little over a week now so any kind of help on this would be greatly appreciated :)

CodePudding user response:

Thanks to Toan Quoc Ho I found out that there was nothing wrong with my CORS config.

Honestly, I do not know why I got and am still getting this error when doing it this way but I found a way around it.

The request now works perfectly. All I did was stop using fetch and use Axios instead to make the request.

That's really all I did and now it works for some reason. Maybe my fetch request was wrong in some way. Who knows

  • Related