48

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);
        })
}
Reza Heidari
  • 1,192
  • 2
  • 18
  • 23
dcielak
  • 605
  • 1
  • 5
  • 8
  • 1
    when you trying to make request from different domain (xxx in your case)the browser not allow to send such request. if xxx is your server - you can configure it to send the headers that allows cros domain request – happyZZR1400 Apr 15 '20 at 21:14
  • Does this answer your question? [How does Access-Control-Allow-Origin header work?](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work) – Heretic Monkey Apr 15 '20 at 21:15
  • I thought localhost was now granted an exception from CORS restrictions on modern browsers including Chrome. You are pulling in your HTML directly from a web server and not from a local source file are you? – selbie Apr 15 '20 at 21:22
  • Hi, how can i do the same in next js? since next provides auth apis itself, how do I add the `access-control-allow-origin` there? – Muskan Paliwal Aug 16 '23 at 05:46

15 Answers15

29

try using ''no-cors' mode.

fetch('http://localhost:8080/example', {
            mode: 'no-cors',
            method: "post",
            headers: {
                 "Content-Type": "application/json"
            },
            body: JSON.stringify(ob)
 })
Thej
  • 417
  • 4
  • 6
  • 8
    What would be the point of a security system with a button saying "disable me" on the outside? See [Trying to use fetch and pass in mode: no-cors](https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors/43268098) — `{ mode: 'no-cors' }` makes things *worse*. – K.K Designs Feb 09 '22 at 05:33
  • Couldn't a bad actor (who's trying to make a request to `evil-website.com/api/hack`) just set the header `'Access-Control-Allow-Origin', '*'` and then they'll be able to make requests to their evil page from whatever page they want? What is CORS preventing? Never mind, [I was looking at it backwards](https://security.stackexchange.com/questions/108835/how-does-cors-prevent-xss). – sleighty Jul 27 '22 at 23:47
6

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

gandharv garg
  • 1,781
  • 12
  • 17
4

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

const cors = require("cors");
app.use(cors());
M.S
  • 121
  • 1
  • 5
4

You must install cors.

npm install cors

inside the main scripts index.js or app.js

const cors = require("cors");
app.use(cors());
Ahmed Elgammudi
  • 642
  • 7
  • 15
1

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", "*")
}) 
General Grievance
  • 4,555
  • 31
  • 31
  • 45
1

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.)

Dream180
  • 180
  • 1
  • 13
1

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

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.

0

The middleware should be like this.

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

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

  • 1
    Hello Habibur Rahman =) Welcome to StackOverfollow. Im happy to assist you with any queries you may have regarding using this Platform. One thing thats allways a great benifit to others is to add comments to your code sameplates to allow you to reach a loarger audience. That being said, try and formate your code blocks with the ` symbole i.e using it in one line just your code between the backticks `Hollo World!` if you need a larger code block you can surround your block off code with 3 backticks and the begening of the block snd 3 at the end i.e ``` If (this == that) { // computed value } – 0xe1λ7r May 08 '22 at 16:48
0

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

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

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 02 '22 at 06:41
0

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 );
            } );
StealthTrails
  • 2,281
  • 8
  • 43
  • 67
0

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.

0

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

Sarang
  • 2,143
  • 24
  • 21
-1

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: header })
      .then((res) => res.json())
      .then((data) => console.log(data));

This will resolve the issue