如何将getAccessToken与fetch函数集成,将数据从DRF后端加载到前端?

2024-04-24 17:02:19 发布

您现在位置:Python中文网/ 问答频道 /正文

反应新手在这里,但精通Django。我有一个简单的提取功能,工作得很好,但当时我的项目没有涉及登录验证。现在我已经配置了登录系统,我的后端拒绝使用任何访问令牌服务请求。我的登录验证对我来说是非常新的,或多或少是从某处复制的。我正试着去理解它,但却无法理解。我只需要知道如何转换我的简单fetch函数,将getAccessToken和请求一起包含在它的头中,以便我的后端为该请求提供服务。你知道吗

下面是我以前使用的简单fetch函数:

class all_orders extends Component {
  state = {
    todos: []
  };

  async componentDidMount() {
    try {
      const res = await fetch('http://127.0.0.1:8000/api/allorders/'); // fetching the data from api, before the page loaded
      const todos = await res.json();
      console.log(todos);
      this.setState({
        todos
      });
    } catch (e) {
      console.log(e);
    }
  }

我的新登录JWT认证系统工作得很好,但我以前的代码不工作,我不断得到错误

"detail": "Authentication credentials were not provided."

这是accesstoken,我无法与我的preivous fetch函数“组合”:

const getAccessToken = () => {
    return new Promise(async (resolve, reject) => {
        const data = reactLocalStorage.getObject(API_TOKENS);

        if (!data)
            return resolve('No User found');

        let access_token = '';
        const expires = new Date(data.expires * 1000);
        const currentTime = new Date();

        if (expires > currentTime) {
            access_token = data.tokens.access;
        } else {
            try {
                const new_token = await loadOpenUrl(REFRESH_ACCESS_TOKEN, {
                    method: 'post',
                    data: {
                        refresh: data.tokens.refresh,
                    }
                });
                access_token = new_token.access;
                const expires = new_token.expires;

                reactLocalStorage.setObject(API_TOKENS, {
                    tokens: {
                        ...data.tokens,
                        access: access_token
                    },
                    expires: expires
                });

            } catch (e) {
                try {
                    if (e.data.code === "token_not_valid")
                        signINAgainNotification();
                    else
                        errorGettingUserInfoNotification();
                } catch (e) {
                    // pass
                }

                return reject('Error refreshing token', e);
            }
        }

        return resolve(access_token);
    });
};

Tags: 函数tokennewdatareturnaccessfetchawait
1条回答
网友
1楼 · 发布于 2024-04-24 17:02:19

如果您正在寻找如何在fetch请求中传递头的方法,那么很简单:

await fetch('http://127.0.0.1:8000/api/allorders/', {
 headers: {
   // your headers there as pair key-value, matching what your API is expecting, for example:
   'details': getAccessToken()
  }
})

只是别忘了导入getAccessToken常量,如果这会把它放在另一个文件中,我相信这就是它。Some reading on Fetch method

相关问题 更多 >