【问题标题】:Getting 400 Error while Authenticating user credentials using fetch API使用 fetch API 验证用户凭据时出现 400 错误
【发布时间】:2021-09-12 13:21:55
【问题描述】:

我使用 asp.net core 作为后端并作为前端做出反应。我正在使用 fetch API 来验证用户凭据。

但是当我尝试登录时,我收到了 400 错误。邮递员一切正常。

这是我的反应代码:

 const submitLoginForm = async (e) => {
    e.preventDefault();
    await fetch("https://localhost:44316/api/auth/login", {
      method: 'POST',
      headers: {"Content-Type": "application/json"},
      credentials: 'include',
      body: JSON.stringify({
        email,
        password,
      })
    });

    setRedirectTo(true);

  };

我在表单提交时调用了上述函数。

【问题讨论】:

  • 是否正在发送 XSRF 令牌(在 cookie / headers 中)?我看到你有 credentials: include 但请仔细检查它是否真的发送了。
  • 它被包含是因为我正在从服务器获取cookie

标签: reactjs .net asp.net-core fetch fetch-api


【解决方案1】:

只需在标题部分添加 => Accept: "application/json"

const submitLoginForm = async (e) => {
    e.preventDefault();
    await fetch("https://localhost:44316/api/auth/login", {
      method: 'POST',
      headers: {
        "Accept": "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        email,
        password,
      })
    });

    setRedirectTo(true);

  };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2023-02-19
    相关资源
    最近更新 更多