Question

Node.js server CORS Failed

Hello,

I have a 1-click LAMP Droplet (Ubuntu). I’ve installed Node.js on it and I’ve added an express.js application. With PM2 I made it run successfully on port 3002, if I use sudo pm2 list I can see that is online. I’m trying to reach endpoints on this running express.js app from my React website (which is on the same server), but I get CORS Failed as I see on Network tab(browser inspector window).

My express.js app has cors:

const express = require('express');
var cors = require('cors');
const app = express();

app.use(cors());
app.use(express.json());

And in React, I’m doing the request like this:

await fetch('https://localhost:3002/contacts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    }).then(response => response.json())
    .then(data => {
      console.log(data);
    }).catch((error) => {
      console.log(error);
    });

Ubuntu version: 20.04.2 LTS (Focal Fossa) PM2 version: 5.1.2 Node.js version: 16.13.1

Is something that I’m missing?

Thanks alot.


Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

Hello,

I believe that a possible explanation would be that you are using https://localhost:3002 rather than http://localhost:3002. Note the extra s.

But as your Node app is running on http you are seeing the cors error.

Let me know how it goes!

Best,

Bobby