ablaszkiewicz1
ablaszkiewicz1

Reputation: 984

React - fetching from API, CORS policy error

I have quite common problem in my React recipe app. This is the code of error. Error code:

Access to fetch at 'http://www.recipepuppy.com/api/?i=onions,garlic&q=omelet&p=3' (redirected from 'http://localhost:3000/api/?i=onions,garlic&q=omelet&p=3') 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 code to fetch (worked with another API):

const fetchItems = async () => {
    const data = await fetch(`api/?i=onions,garlic&q=omelet&p=3`);
    console.log(data);
};

What I have tried:
1) standard approach - fetch full URL - didn't work
2) read about setting up proxy, so I have added this in package.json

"proxy": "http://recipepuppy.com",

and shortened the link - gives the same error
3) published the site not to request from localhost - didn't work as well
4) used {mode: 'no-cors'} - fetch returned empty object

Basically the fetch does work - here is the working link (just fire it up in the browser)

http://recipepuppy.com/api/?i=onions,garlic&q=omelet&p=3

Any sugestions? I am using npx-create-app in order to use react.

Upvotes: 0

Views: 235

Answers (3)

Youssef Egla
Youssef Egla

Reputation: 1601

You need to modify Access-Control-Allow-Origin header that's sent from your development server; I assume webpack.

Add this to your webpack.config if you manually configured it.

devServer: {
    headers: {
      'Access-Control-Allow-Origin': '*'
    }
  }

asterisk allows all, you can only specify one or all, refer to this link on mdn

On the backend server for the website you are requesting from you need to enable cors, you can easily do that with cors module if you are using node with express

Upvotes: 1

stefano.orlando
stefano.orlando

Reputation: 90

When you develop in localhost you need to use a so-called CORS proxy, like this

You can easily use it via npx writing in a shell

$ npx corsproxy

It will provide you on localhost:1337 a proxy that will resolve all CORS-type requests.

So in your application you can change the url of the resource with http://localhost:1337/www.recipepuppy.com/api/?i=onions,garlic&q=omelet&p=3.

Since the server will answer you with JSON, after using fetch you have to use fetch(opt).then(res => res.json()) to access the server response in JSON format!

const fetchItems = async () => {
    const data = await fetch(`http://localhost:1337/www.recipepuppy.com/api/?i=onions,garlic&q=omelet&p=3`).then(data => data.json())
    console.log(data);
};

Upvotes: 0

Adrian Pascu
Adrian Pascu

Reputation: 1039

Try console.log(await data.json())

Upvotes: 0

Related Questions