Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute wont work

I am having this problem when trying to use withCredentials that it tells me that I need

Access to XMLHttpRequest at 'http://localhost:3005/api/v1/user' from origin 'http://localhost:3000' 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Uncaught (in promise) AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
async function getUser() {
    const user = await axios.get("http://localhost:3005/api/v1/user", {
      withCredentials: true, headers: {
        'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
      }
    });
    console.log(user)
  }
  useEffect(() => {
    getUser();
  }, [])

Researching this people are telling me that I need to activate cors on the server. But from what I can tell I have already done that by doing this + npm I cors.

const cors = require('cors')
var app = express();
const corsOptions ={
    origin:'*', 
    credentials:true,            //access-control-allow-credentials:true
    optionSuccessStatus:200,
 }
app.use(cors(corsOptions))

If I remove the withCredentials everything works fine the problem is that I need the connect.sid cookie on the server in order to log in the user.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I have had this problem before. Solved it by changing the * to [‘http://localhost:3000’%5D

So your code should say:

const cors = require('cors')
var app = express();
const corsOptions ={
    origin:['http://localhost:3000'], 
    credentials:true,            //access-control-allow-credentials:true
    optionSuccessStatus:200,
 }
app.use(cors(corsOptions))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading