Search code examples
javascriptnode.jsexpresscors

CORS hell is preventing me from moving forward with a personal project


I am simply trying to create a LOCAL connection between a computer and a Raspberry Pi. Super important preamble to understand before people start talking to me about internet security and stuff. No, this thing I am building WILL NEVER be connected online freely.

On the Pi, I am running a NodeJS server which is intended to receive POSTs to trigger some stuff on the Pi's GPIO.

On the other computer, I am running a LOCAL web page which has the UI to trigger the requests.

Basic flow diagram:

COMP -> fetch() ===> PI -> GPIO

All could be running well, but I can't manage to reach the Pi server because CORS. I am not trying to understand CORS (please don't give me a lecture on web security or its history, I see this too often in tutorials, this is not what I am looking for).

I am trying to figure out what parameters I am not setting properly in either the sending of the request, or the Pi server's handling of the request.

Excerpt from the front-end JS:

function postState(value) {
  const options = {
    method: 'POST',
    body: JSON.stringify({ state: value }),
    headers: {
      'Content-Type': 'application/json'
    },
  };

  fetch(TOGGLE_URL, options)
    .then(res => res.json())
    .then(res => console.log(res))
    .catch(err => console.error(err));
}

And here is the server JS so far:

require('dotenv').config();

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

const port = process.env.API_PORT;


// api
app.post('/toggle', (req, res) => {
  const state = req.query.state;
  console.log('state from body:', state);


  res.writeHead(
    200,
    {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': '*',
      'Access-Control-Request-Method': 'GET,POST',
    }
  );
});


// setup + startup
app.use(express.json());

app.listen(port, () => {
  console.log(`Listening on port ${ port }`);
});

Thanks in advance for tips and guidance in plain words.


Edit: I corrected to app.post


Providing details to people who ask questions:

Q: "Maybe you at least got an actual CORS error message for us then?" - CBroe

A: Good suggestion:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.68.75:6464/toggle. (Reason: CORS request did not succeed). Status code: (null).


Q: "Where do you enable/configure CORS in your server?" – Prerak Sola

A: I am not a server/backend person, thus I likely do not know how to do this. This probably falls under the "I am trying to figure out what parameters I am not setting properly..." of my question. I tried reading about this for ExpressJS, but could not understand any of the tutorials about this. Hence why I am asking humans for assistance.


If anyone gets to this part, I managed to get it working, likely thanks to Lowsec-code's suggestion of using

const cors = require('cors');
app.use(cors());

It seems that the issue was using Firefox as a browser for calling the API, because when I tried with Safari and Chrome, they both managed to call the server and not get an error. No way to manage to do that kind of local calls on Firefox, no matter how you change the about:config.


Solution

  • simple way to skip cors issues is install cors package on your express server and use it like this and add this in top of your express middlewares and routes:

    const cors=require("cors")
    
    app.use(cors())
    
    
    

    by default it fix must standard cors issues but you can give options as object to cors function.