Search code examples
reactjscors

Cors and React with no local server


I am trying to fetch data from https://dummyjson.com/auth/login

My request looks like this:

    const getArticles = async () => {
      const data = await fetch("https://dummyjson.com/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json",'Access-Control-Allow-Origin': 'http://localhost:3000', 'Access-Control-Allow-Credentials': 'true' },
        body: JSON.stringify({
          username: "emilys",
          password: "emilyspass",
          expiresInMins: 30, // optional, defaults to 60
        }),
        credentials: "include", // Include cookies (e.g., accessToken) in the request
      });
    };

I am getting the error below: enter image description here


Solution

  • Remove credentials: "include". That triggers an OPTIONS call, which dummyjson doesn't include as an approved method in their access-control-allow-methods header (allowed methods: GET,HEAD,PUT,PATCH,POST,DELETE). Unless there is a reason you need to pass cookies along, there's no need to use credentials in your request.

    This works for me:

    const getArticles = async () => {
      const data = await fetch("https://dummyjson.com/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json",'Access-Control-Allow-Origin': 'http://localhost:3000', 'Access-Control-Allow-Credentials': 'true' },
        body: JSON.stringify({
          username: "emilys",
          password: "emilyspass",
          expiresInMins: 30, // optional, defaults to 60
        })
      });
    };
    

    ...and I received the following response:

    {
      "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJlbWlseXMiLCJlbWFpbCI6ImVtaWx5LmpvaG5zb25AeC5kdW1teWpzb24uY29tIiwiZmlyc3ROYW1lIjoiRW1pbHkiLCJsYXN0TmFtZSI6IkpvaG5zb24iLCJnZW5kZXIiOiJmZW1hbGUiLCJpbWFnZSI6Imh0dHBzOi8vZHVtbXlqc29uLmNvbS9pY29uL2VtaWx5cy8xMjgiLCJpYXQiOjE3MjcyOTc4MTAsImV4cCI6MTcyNzI5OTYxMH0.FdD1MZ1AppmkC05XiYhu1hT6AK_6WC4f0rc62q31-aA",
      "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJlbWlseXMiLCJlbWFpbCI6ImVtaWx5LmpvaG5zb25AeC5kdW1teWpzb24uY29tIiwiZmlyc3ROYW1lIjoiRW1pbHkiLCJsYXN0TmFtZSI6IkpvaG5zb24iLCJnZW5kZXIiOiJmZW1hbGUiLCJpbWFnZSI6Imh0dHBzOi8vZHVtbXlqc29uLmNvbS9pY29uL2VtaWx5cy8xMjgiLCJpYXQiOjE3MjcyOTc4MTAsImV4cCI6MTcyOTg4OTgxMH0.lfjT0OIWFsL5M_xFlZlBQcISVfr90GxJXytXbfLo5s0",
      "id": 1,
      "username": "emilys",
      "email": "[email protected]",
      "firstName": "Emily",
      "lastName": "Johnson",
      "gender": "female",
      "image": "https://dummyjson.com/icon/emilys/128"
    }
    

    I hope this helps.