我正在尝试使用一个api,其中我有用户名和密码,通过这段代码,我可以获得身份验证令牌
axios.post(this.apiUrl,
{
username : 'xxx',
password : 'yyy'
},
)
.then((respond)=>{
this.token = respond.data.token
console.log(this.token)
})
.catch((error)=>{
console.log('errore',error)
})因为我需要这个令牌来访问同一个Api中的其他路由,所以我应该在其他请求中重用它,如本例中所示。
axios.post(this.apiUrl+(otherEndPoint),{body},
{
headers:{
"authorization":this.token
}
},
)
.then((respond)=>{
r = respond.data.token
console.log(r)
})
.catch((error)=>{
console.log('errore',error)
})但这不管用,有人可以帮我
发布于 2022-04-29 15:55:47
在不了解如何设置项目的情况下,关于如何进行项目设置的要点如下:
get、post等代码:
// Import axios module
import axios from 'axios';
// Set default header. e.g, X-API-KEY
axios.defaults.headers['X-API-KEY'] = 'some-api-key';
// Use axios as you would normally
axios.get('http://example.com/secure-endpoint')
.then(res => console.log(res.data))
.catch(err => console.log(err));就你的情况而言:
import axios from 'axios';
// ... somewhere in code
// Get api-key from server
const username = 'someUsername';
const password = 'somePassword';
axios.post('http://example.com/api/getKey', {
username,
password
}).then(res => {
axios.defaults.headers['x-api-key'] = res.data.apiKey;
})
.catch(err => console.log(err));
// ...
// ... somewhere else in code
axios.get('http://example.com/secure-endpoint')
.then(res => console.log(res.data))
.catch(err => console.log(err));
// ...这些只是例子。根据您的项目结构和需求进行更改。
https://stackoverflow.com/questions/72060067
复制相似问题