Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
  })

}

like image 592
dcielak Avatar asked Apr 15 '20 21:04

dcielak


People also ask

How to solve CORS issue in JavaScript fetch?

To solve the "TypeError: Failed to fetch", make sure to pass the correct configuration to the fetch method, including the URL, HTTP method and headers, and verify that the server you're making a request to is setting the correct CORS headers with the response. Copied!

How do I fix access to XMLHttpRequest at origin has blocked by CORS policy?

How Access to XMLHttpRequest has been blocked by CORS policy Redirect is not allowed for a preflight request only one route Error Occurs ? Just Disable CORS policy security. Go to google extension and search for Allow-Control-Allow-Origin. Now add it to chrome and enable.

How to avoid CORS JavaScript?

Handling CORS You can use the Access-Control-Allow-Origin to specify which origin the client app must be requesting from, you can use Access-Control-Allow-Headers to specify which header(s) the client app can provide, you can use Access-Control-Allow-Method to specify which HTTP method(s) the client app can use e.t.c.


1 Answers

try using ''no-cors' mode.

fetch('http://localhost:8080/example', {
            mode: 'no-cors',
            method: "post",
            headers: {
                 "Content-Type": "application/json"
            },
            body: JSON.stringify(ob)
 })
like image 71
Thej Avatar answered Sep 17 '22 16:09

Thej