Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to fetch at *** from origin *** has been blocked by CORS policy: No 'Access-Control-Allow-Origin'

I have error

Access to fetch at 'http://localhost:5000/admin/authenticate' from origin 'http://localhost:3000' 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.

My ApiManager

function login(username, password) {
    const requestOptions = {
        method: 'POST',
        headers: {    
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*' },
        body: JSON.stringify({ username, password })};

    return fetch(`http://localhost:5000/admin/authenticate`, requestOptions)
        .then(handleResponse)
        .then(user => {
            // store user details and jwt token in local storage to keep user logged in between page refreshes
            localStorage.setItem('user', JSON.stringify(user));
            return user;
        }
    );
}

In Backend Asp.Net Core 2.2 (Startup.cs) I write:

services.AddCors(options =>
{
    options.AddPolicy(
        _corsName,
        builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials(); });}
);
like image 248
Yura Morozov Avatar asked Feb 20 '19 21:02

Yura Morozov


1 Answers

FOR NODE EXPRESS GRAPHQL RESTAPI Add this header middleware to avoid CORS and any POST or OPTIONS error

app.use((req, res, next) => {
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader(
        "Access-Control-Allow-Methods",
        "OPTIONS, GET, POST, PUT, PATCH, DELETE"
      );
      res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
      if (req.method === "OPTIONS") {
        return res.sendStatus(200);
      }
      next();
    });
like image 160
Smit Gajera Avatar answered Sep 27 '22 00:09

Smit Gajera