dcielak
dcielak

Reputation: 815

Access to fetch at from origin 'http://localhost:3000' has been blocked by CORS policy

Adding to the database shows the error. What should I do?

Access to fetch at 'http:xxx' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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 function:

addItem = (e) => {
    e.preventDefault();
    const ob = {
        X: 53.0331258,
        Y: 18.7155611,
    }
    fetch("http://xxx", {
            method: "post",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(ob)
        })
        .then(res => res.json())
        .then(res => {
            console.log(res);
        })
}

Upvotes: 69

Views: 326488

Answers (20)

Prasad Gharge
Prasad Gharge

Reputation: 1

function buildResponse(statusCode, body) {
    return {
        statusCode: statusCode,
        headers: {
             "Access-Control-Allow-Headers" : "Content-Type",
              "Access-Control-Allow-Origin": "*",
            'Content-Type': 'application/json',
             "Access-Control-Allow-Methods": "OPTIONS,POST,GET,PATCH"
        },
        body: JSON.stringify(body),
    };
}

Node index. Js

Upvotes: 0

שמעון פוקס
שמעון פוקס

Reputation: 49

I also had the same error. And in the end my solution was that I mistakenly used the application's middleware before cors

app.use(
 cors({origin: 'http://localhost:5173', credentials: true})
);

app.use(session(sessionConfig));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(authMiddleware);

Maybe this will help someone...

Upvotes: 0

Vinicius Cardoso
Vinicius Cardoso

Reputation: 1086

Resolved my issue by specifying the OPTIONS method. See the relevant part of the code below:

const headers = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
  "Access-Control-Allow-Methods": "OPTIONS,POST"
};

if (event.httpMethod === 'OPTIONS') {
  return {
    statusCode: 200,
    headers: headers,
    body: JSON.stringify({})
  };
}

if (event.httpMethod !== 'POST') {
  throw new Error(`signIn only accepts POST method, you tried: ${event.httpMethod}`);
}

Upvotes: 0

Jay Panchal
Jay Panchal

Reputation: 11

make a new variable called header:

const header = new Headers({ "Access-Control-Allow-Origin": "*" });

pass this variable as an object in fetch:

fetch(url, { header })
      .then((res) => res.json())
      .then((data) => console.log(data));

This will resolve the issue

Upvotes: -1

Priyanshu kuntal
Priyanshu kuntal

Reputation: 107

I don't know if it will work for you or not but manually adding cors worked for me.

instead of this

const corsOption = {
  credentials: true,
  origin: ["https://example.com/"],
}
app.use(cors(corsOption));

try this

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'https://example.com');
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  next();
});```

Upvotes: 0

Naman Chandak
Naman Chandak

Reputation: 19

This error is caused because your server not allow client host to generate a request.

if you are using springboot then try

@PostMapping("/create-user")
@CrossOrigin(origins = "http://localhost:4200")

"http://localhost:4200" instead of this write address of your server.

Upvotes: 0

saiteja kalva
saiteja kalva

Reputation: 21

solution 1: if you are using spring boot at the backend try using cross orgin annotation while handling post and get requests.

@CrossOrigin(origins = "http://localhost:3000")

solution 2: Try removing web security dependency in your backend, or you can pass username and password in the header, as shown below

useEffect(() => {
    // Replace with your API endpoint
    const apiUrl = 'https://your-backend-api-url.com/data';

    // Replace with your Basic Authentication credentials
    const username = 'your-username';
    const password = 'your-password';
    const basicAuthHeader = 'Basic ' + btoa(username + ':' + password);

    fetch(apiUrl, {
      method: 'GET',
      headers: {
        'Authorization': basicAuthHeader
      }
    })
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => console.error('Error fetching data:', error));
  }, []);

i hope this solves your problem.

Upvotes: 2

Sarang
Sarang

Reputation: 2713

In case you are getting this on content of a AWS S3 bucket, Go to Bucket -> Permissions -> CORS from the AWS S3 Console and add the following:

[
    {
        "AllowedHeaders": [],
        "AllowedMethods": [
            "GET"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": []
    }
]

Be careful of the consequences though - this will allow the content to be hosted within any website. You can add other methods if you need to like POST,PATCH in addition to the GET

Upvotes: 1

Kuda Christine
Kuda Christine

Reputation: 31

Simplest solution: Got this from AWS docs

  1. In you lambda function's code
  2. Add this in your function that returns a response

function buildResponse(statusCode, body) {
    return {
        statusCode: statusCode,
        headers: {
             "Access-Control-Allow-Headers" : "Content-Type",
              "Access-Control-Allow-Origin": "*",
            'Content-Type': 'application/json',
             "Access-Control-Allow-Methods": "OPTIONS,POST,GET,PATCH"
        },
        body: JSON.stringify(body),
    };
}

Upvotes: 3

shadi makhoul
shadi makhoul

Reputation: 11

Actually it's more efficient to fix this bug from the server side like this:

npm install cors

inside the post operation:

app.post("/...", (req, res) =>{
  res.set('Access-Control-Allow-Origin', '*');
//whatever you want here
}

you can read this article https://www.stackhawk.com/blog/react-cors-guide-what-it-is-and-how-to-enable-it/#enable-cors-on-server-side

OR you can easily convert the client side to work on the same domain with the server side by adding in the package.json (client side)"proxy" of the server domain like this:

"proxy": "http://xxxx/"

in this case you don't have to add the domain name in each request anymore.

and the last solution "it's not recommended" by adding {"mode": "no-cors"} to your request.

Upvotes: 0

StealthTrails
StealthTrails

Reputation: 2415

In WordPress version 6 I solved the issue by using the mode option available in fetch api here

apiFetch( { mode: 'no-cors', url: 'https://api.example.com/?q=' + attributes.search_string } ).then( ( posts ) => {
                console.log( posts );
            } );

Upvotes: 0

ELMFouad
ELMFouad

Reputation: 1

try to add annotation @CrossOrigin , its worked for me .

@RestController @RequestMapping(value="") @CrossOrigin

Upvotes: 0

Dream180
Dream180

Reputation: 200

Try using the following code:

var corsOptions = {
  origin: "http://localhost:3000"
};

app.use(cors(corsOptions));

You should copy in server.js(or app.js)

(I've experienced the exact same problem as this one. I was able to solve the problem by adding the following code to server.js.)

Upvotes: 3

Habibur Rahman
Habibur Rahman

Reputation: 1

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

i use this but can't solve this problem.

app.use((req, res, next) => { res.header({"Access-Control-Allow-Origin": "*"}); next(); }) when use this code than solve this problem

Upvotes: 0

Ahmed Elgammudi
Ahmed Elgammudi

Reputation: 746

You must install cors.

npm install cors

inside the main scripts index.js or app.js

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

Upvotes: 4

M.S
M.S

Reputation: 181

I resolved the issue by installing the cors node module and adding this on the requested server

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

Upvotes: 8

ABDERRAHMANE OUALI
ABDERRAHMANE OUALI

Reputation: 931

For browser CORS is enabled by default and you need to tell the Browser it's ok for send a request to server that not served your client-side app ( static files ).

if you use RestFul API with node and express add this middleware to your file

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*")
}) 

Upvotes: 1

umess
umess

Reputation: 31

The middleware should be like this.

app.use((req, res, next) => {
  res.header({"Access-Control-Allow-Origin": "*"});
  next();
}) 

Upvotes: 0

Thej
Thej

Reputation: 615

try using ''no-cors' mode.

fetch('http://localhost:8080/example', {
            mode: 'no-cors',
            method: "post",
            headers: {
                 "Content-Type": "application/json"
            },
            body: JSON.stringify(ob)
 })

Upvotes: 48

gandharv garg
gandharv garg

Reputation: 2171

Your server should respond with a response that looks like below

Access-Control-Allow-Origin: https://localhost:3000

Untill you are able to configure that as a workaround you can install the below chrome extension to resume your testing

https://chrome.google.com/webstore/detail/who-cors/hnlimanpjeeomjnpdglldcnpkppmndbp?hl=en-GB

But the above is only a workaround to continue development

I would suggest you read this article for understanding CORS https://javascript.info/fetch-crossorigin

Upvotes: 11

Related Questions