-2

Hi I have a backend hosted at heroku and frontend in Netlify when I am trying to connect it is giving me the following error Access to fetch at 'https://abc.herokuapp.com/profile' from origin 'https://www.exam.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

In client call i have added

    const callUserPage = async () => {
        try {
            const res = await fetch("https://abc.herokuapp.com/profile", {
                method: "GET",
                headers: {
                    Accept: "appllication/json",
                    "Content-Type": "application/json",
                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Methods":
                        "DELETE, POST, GET, OPTIONS",
                    "Access-Control-Allow-Headers":
                        "Content-Type, Authorization, X-Requested-With",
                },
                credentials: "include",
            });
            const data = await res.json();
            setUserData(data);
            if (!res.status === 200) {
                const error = new Error(res.error);
                throw error;
            }
        } catch (error) {
            navigate("/login");
        }
    };
jabaa
  • 3,902
  • 3
  • 6
  • 24
Shubham Raj
  • 101
  • 6
  • Start by taking all the `Access-Control` headers from the request. They are response headers. Your JS can't give itself permission to access data from other origins! Then go and look at your server side code. – Quentin May 16 '22 at 20:14
  • Please don't modify your question and apply solutions from answers. – jabaa May 16 '22 at 20:31

1 Answers1

-1

you should try installing npm install cors library. Here's the library

Now in your backend index or server file do the following:

import cors from 'cors';
...

app.use(cors()); //app name should've different if you declare it with another name
...

Let me know if this library solve your problem :)

cblnpa
  • 131
  • 8
  • I have added it in my server end it is like var cors = require("cors"); var app = express(); app.use(cors()); do i need to install it on client side as well ? – Shubham Raj May 16 '22 at 20:20
  • no, you don't need to install it on client side. Try to stop the server, render again or using the cors options let whitelist = ['http://example1.com'] (see the documentation) – cblnpa May 16 '22 at 21:17