React如何获取accessToken?

React how to get accessToken?

我想发送 post 并进行提取。但我收到 401 错误:www-authenticate: Bearer error="invalid_token"。 我正在使用 Userfront.accessToken() 但它没有用。

如何获得用于承载认证的accestoken?

const submit = (e) => {
    e.preventDefault();
    const data = new FormData(form.current);
    fetch(process.env.REACT_APP_ENDPOINT + "user/me/contract", {
      method: "POST",
      body: data,
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${Userfront.accessToken()}`,
      },
    }).then((res) => res.json());
  };

注:

console.log(`Bearer ${Userfront.accessToken()}`);

Bearer [object Object]

JSON.stringify(Userfront.accessToken()) 请对该对象进行字符串化以了解那里发生了什么,然后如果从该函数返回 accessToken 则放入该字符串。

刚刚在文档中了解到;

To handle a request like this -Userfront.accessToken()-, your backend should read the JWT from the Authorization header and verify that it is valid using the public key found in your Userfront dashboard.

https://userfront.com/guide/auth/

fetch('https://api.example.com', {
  method: 'GET'
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${Userfront.tokens.accessToken}`
  }
});

你能试试这个吗?我从 https://userfront.com/guide/auth/

看到这个
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${Userfront.tokens.accessToken}`
  }

谢谢大家的回答。

Authorization: `Bearer ${localStorage.getItem("fray_access_token")}`,

在此应用程序中,令牌获得了不同的名称。 当我检查时,我使用它并且它有效!