Question

Node.js server CORS Failed

Posted December 14, 2021 145 views
UbuntuNode.jsLAMP StackReact

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

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