Home > Software design >  How do I fix CORS Error when Trying to fetch data from SERP API into my react app
How do I fix CORS Error when Trying to fetch data from SERP API into my react app

Time:03-27

I am trying to fetch data from SERP API to fetch Job_Results, on postman, I am able to fetch my data but when I try to fetch it using Axios, I get CORS Error even after specifying Proxy in package.json and passing appropriate headers.

This is my code snippet:

let config = {
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*"
      },
    };
    const data = await axios.get(
      "https://serpapi.com/search.json?engine=google_jobs&q=internship new delhi&hl=en&api_key=xxxxxx",
      config
    );

CodePudding user response:

As per this https://forum.serpapi.com/feature-requests/p/add-http-cors-headers serpapi doesn't allow cross-origin requests from the browsers

So you need to use this in Server side code only, You cannot consume this API in React or any frontend application

For example To get https://serpapi.com/search.json?engine=google_jobs&q=internship new delhi&hl=en&api_key=xxxxxx"

You need to create a endpoint in server side yourdomain.com/requiredparams that takes params and pass to https://serpapi.com/search.json and request data

So instead of calling serpapi you call your own API and Server will make request to serpapi and give response If you follow this way your API key is also safe

  • Related