没有本地服务器的 Cors 和 React

问题描述 投票:0回答:1

我正在尝试从 https://dummyjson.com/auth/login

获取数据

我的要求是这样的:

    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
      });
    };

我收到以下错误: enter image description here

reactjs cors
1个回答
0
投票

删除

credentials: "include"
。这会触发
OPTIONS
调用,dummyjson 不将其作为已批准的方法包含在其
access-control-allow-methods
标头中(允许的方法:
GET
HEAD
PUT
PATCH
POST
DELETE
)。除非您有特殊原因需要传递 cookie,否则无需在请求中使用
credentials

这对我有用:

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
    })
  });
};

...我收到以下回复:

{
  "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"
}

我希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.