在我的反应应用程序中,我使用axios来执行REST api请求。
但它无法使用请求发送Authorization标头。
这是我的代码:
tokenPayload() {
let config = {
headers: {
'Authorization': 'Bearer ' + validToken()
}
}
Axios.post(
'http://localhost:8000/api/v1/get_token_payloads',
config
)
.then( ( response ) => {
console.log( response )
} )
.catch()
}
这里的validToken()
方法只是从浏览器存储中返回令牌。
所有请求都有500错误回复说
无法从请求中解析令牌
从后端。
如何使用每个请求发送授权标头?你会推荐其他任何反应模块吗?
var config = {
headers: {'Authorization': "bearer " + token}
};
var bodyParameters = {
key: "value"
}
Axios.post(
'http://localhost:8000/api/v1/get_token_payloads',
bodyParameters,
config
).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
});
第一个参数是URL。 第二个是将根据您的请求发送的JSON正文。 第三个参数是标题(以及其他内容)。这也是JSON。
axios.post
的第二个参数是data
(不是config
)。 config
是第三个参数。请查看详细信息:https://github.com/mzabriskie/axios#axiosposturl-data-config
以下是在axios中设置授权令牌的独特方法。将配置设置为每个axios调用都不是一个好主意,您可以通过以下方式更改默认授权令牌:
const axios = require('axios');
axios.defaults.baseURL = 'http://localhost:1010/'
axios.defaults.headers.common = {'Authorization': `bearer ${token}`}
编辑
某些API要求将承载写为承载,因此您可以执行以下操作:
axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}
现在您不需要为每个API调用设置配置。现在授权令牌被设置为每个axios调用。
您可以创建一次配置并在任何地方使用它。
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'Authorization': 'Bearer '+token}
});
instance.get('/path')
.then(response => {
return response.data;
})
通过使用axios拦截器
const service = axios.create({
timeout: 20000, // request timeout
});
// request interceptor
service.interceptors.request.use(
config => {
// Do something before request is sent
config.headers['Authorization'] = 'bearer ' + getToken()
return config
},
error => {
Promise.reject(error)
}
)
如果您想在标头中传递令牌后想要一些数据,那么请尝试使用此代码
const api = 'your api';
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
console.log(error)
});
这也是我所面对的。你传递的令牌不正确。
只需对令牌进行硬编码并通过,您将获得正确的响应。但如果令牌没有在单引号中传递,那么它肯定会失败。它必须采用'授权'格式:'Bearer YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZZNNI1MmI4MDJkNQ',其中必须存在Bearer一个空格后,也在单引号内,这非常重要。
var token = 'YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZjN2I1MmI4MDJkNQ';
var headers = {
'Authorization': 'Bearer '+ token,
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
}
IMP:上面的代码可以工作但是如果你发布类似的东西:
'授权':'持票人'+ YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjVlOTQ5YMmQ5ZjMwYjA0YmEzZmZNNII1MmI4MDJkNQ,它会失败
或-----以下代码也将失败,我希望你了解基本的区别
var token = YzE5ZTdiMjVlYzM5NjA2MGJkZTM5NjA0YmEzZmZjN2I1MmI4MDJkNQ;
var headers = {
'Authorization': 'Bearer '+ token,
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
}