Home > OS >  Fetch problem with node.js express server
Fetch problem with node.js express server

Time:05-20

I'm having some trouble with the fetch and node.js. In my frontend when i click a button, i would like to send a post request in order to receive an array from my backend as answer. I'n my backend i'm using node.js with express, in my frontend i'm using the fetch function.

The error that occours is the following:

Access to fetch at 'http://localhost:8080/api' from origin 'real localhost address' 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.

Code Here

const getArray = async() => {
  const data = await fetch ("http://localhost:8080/api");
  const dataJson = await data.json();
  console.log(dataJson)
}

getArray(); 

In my server i've got

app.post("/api", (req,res) => {
    res.sendFile(JSON.stringify(arr));
});

CodePudding user response:

You need to add request options. Please refer to the MDN docs for further information.

CodePudding user response:

As @Kudah said, you should read the docs.

Fetch (and XMLHttpRequest) follow the same-origin policy. This means that browsers restrict cross-origin HTTP requests from within scripts. A cross-origin request occurs when one domain (for example http://example2.com/) requests a resource from a separate domain (for example http://example1.com/).

The easiest way to solve this, (If you don't want to dig too much into this)

const whiteList = [ "https://myRealBackendUrl-1", "https://myRealBackendUrl-2" ];
// you can also pass a string here instead here instead of array
const corsOptions = {
  credentials: true,
  origin: process.env.NODE_ENV !== production ? "http://localhost:4000" : whiteList
  // if you are in a dev environment, you probably want something like localhost
  // http://localhost:4000 is just a demo backend. replace it with your own.
  // if you are in a production environment, for example heroku then your backend 
  // url will be something like http://example.herokuapp.com 
  // in that case `const whiteList = [ "http://example.herokuapp.com" ];`
};

app.use(cors(corsOptions));

The above code should be enough for the normal use case.

There is also callback function, it is if you want to run some function of your own. Don't read it if you dont plan to use any dynamic checking

var corsOptionsDelegate = async (req, callback) => { 
    var corsOptions = { origin: false };
    try {
        // you can do some dynamic check here
        // For example: check database for some conditions then allow access
        if( myDatabaseSays == true ) corsOptions.origin = true;
        else corsOptions.origin = false;
    } catch (err) {
        console.log(err);
        // corsOptions.origin = false;
    }
    callback(null, corsOptions) // chain it
}

Anyway read the docs properly for more info [1]: https://expressjs.com/en/resources/middleware/cors.html

  • Related