Home > other >  The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredential
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredential

Time:08-12

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.

CodePudding user response:

I have had this problem before. Solved it by changing the * to ['http://localhost:3000']

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))
  • Related