skip to Main Content

the following problem. I have an Ubuntu web server running a React app. In particular, there are two files in the server file that process the requests made by the website. For some reason, however, it is not possible to make a request to the server as a client.

Server.js:

const express = require('express')
const mysql = require('mysql')
const cors = require('cors')
const bodyParser = require('body-parser');

const app = express()
app.use(cors({
    origin: ['*']
}))
app.use(bodyParser.json());

const db = mysql.createConnection({
    host: '192.168.178.70',
    user: 'webserver',
    password: '123',
    database: 'lanparty',
    port: '3306'
})


app.get('/Ergebnisse', (req, res) => {
    console.log("gotRequest")

    db.query("SELECT * FROM lanparty.match;", (err, data) => {
        if (err) {
            console.log(err)
            res.json(err)
        } else {
            res.json(data)
        }  
    })
})


app.listen(30100, () => {
    console.log("Listening....")
})

Results.js:

import { useEffect } from "react"
import axios from "axios";

export default function Results() {

  useEffect(() => {
    console.log("fetching...")
    axios.get('http://localhost:30100/Results')
      .then(response => response.json())
      .then(data => {
        console.log("data")
        console.log(data)
      })
      .catch((error) => {
        console.error("Error:")
        console.log(error)
      });

  }, [])

  return (
    <div className="pageDiv">

      <h2>Results</h2>

    </div>
  );
}


If I´m making the request directly in the browser ( http://192.168.178.70:30100/Results ) everything works fine, so the server.js should work, but the Request gets blocked if the webserver is the origin.The exact error looks like this:

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

The request in the dev tools looks like this:
description of the error

I tried literally every way of adding the Access-Control-Allow-Origin Header:

  • The way you see in my code right now
  • The way you see in my code right now, but with every possibility to represent localhost (‘localhost’, ‘127.0.0.1’, the ip address of the webserver)
  • In my app.get, in the form of res.setHeader("Access-Control-Allow-Origin", "localhost");
    again I tried "*" and "127.0.0.1"

but non of these worked for me.

Thank you in advance for your time and help 🙂

2

Answers


  1. I had a problem once, mostly it is an error caused if Firefox browsers. there might be an issue in the header or the client or in the server

    List of solutions

    1. setting the header in the server
    
    // set the headers 
    app.use(function (req: Request, res: Response, next: NextFunction) {
      res.header("Access-Control-Allow-Origin", "http://localhost:5173");
      res.header("Access-Control-Allow-Credentials", "true");
      res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
      res.header(
        "Access-Control-Allow-Headers",
        "Origin,X-Requested-With,Content-Type,Accept,content-type,application/json,Authorization",
      );
      next();
    });
    
    // initialize cors 
    app.use(cors({ credentials: true, origin: process.env.NODE_ENV !== "http://localhost:5173" : process.env.HOST as string}));
    
    

    as you can see i use two layers of setting cors

    1. manually setting the headers
    2. using the cors middlewares.

    this works when using HTTP clients and and sometimes still fail on using it in the browser

    1. setting the headers in the client since you are using axios.
    import axios from 'axios';
    export const config = {
      baseURL: 'http://localhost:5000',
      withCredentials: 'include',
      timeout: 8000,
      headers: {
        'Content-Type': 'application/json',
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS"
      },
    };
    
    export const api = create(config);
    export default api;
    

    Sometimes the browser will intentionally fail your request especially when dealing with request like PUT Requests because of some browsers built in security features.

    Login or Signup to reply.
  2. I do not know Node.js but I think I know what your are missing here: you didn’t configure your server to response to preflight request.

    Basically, when client (Results.js) code try to make a CORS request, the browser will fire a preflight request first. The purpose of this request is to verify that your server support CORS as well as which method/origin it supports.

    1. Response to preflight request:
    • Preflight request is a request with the same URL as CORS request, but method = OPTION
    • You need to response to any request with method = "OPTION" with below headers:
      • Access-Control-Allow-Origin: *
      • Access-Control-Allow-Methods: which method you allow for this resource, in your case "GET"
      • Access-Control-Allow-Headers: which headers you allow in the CORS request, as the above answer: "Origin,X-Requested-With,Content-Type,Accept,content-type,application/json,Authorization"
    1. Response to the main CORS request:
    • After the preflight request success, browser will then fire your request in client.js.
    • The response to this request also need to have the same headers as preflight request

    Note: Some browser may require additional headers for it to accept the CORS request. Just read the console log and add proper headers to the response
    For your reference: https://fetch.spec.whatwg.org/#http-responses

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search