React 中的承载身份验证

Bearer Authentication in React

如何在 React 中通过超级代理使用 Bearer Authentication? 我不确定语法,也找不到示例。

我现在做什么

   showTransactionList = () => {
        superagent
            .post('http://193.124.114.46:3001/api/protected/transactions')
            .set({'Authorization': 'Bearer ' + this.state.id_token})
            .accept('application/json')
            .then(res => {
                const posts = JSON.stringify(res.body);
                console.log(posts);
            })
            .catch((err) => {
                console.log(err);
                throw err;                    
            });
    }

谢谢!

尝试使用 .auth('Bearer', this.state.id_token) http://visionmedia.github.io/superagent/#authentication

设置 header 的方式是提供 header 项名称和值,尝试:

showTransactionList = () => {
    superagent
        .post('http://193.124.114.46:3001/api/protected/transactions')
        .set('Authorization', 'Bearer ' + this.state.id_token)
        .accept('application/json')
        .then(res => {
            const posts = JSON.stringify(res.body);
            console.log(posts);
        })
        .catch((err) => {
            console.log(err);
            throw err;                    
        });
}

因此,不要在 header 中设置 object,而是将其作为 2 个参数(名称、值)传递。

而不是将完整的 header 设置为

.set({'Authorization': 'Bearer ' + this.state.id_token})

你可以使用

.auth(this.state.id_token, { type: 'bearer' })