我首先发布以获取令牌,然后将响应保存在本地存储中,如何使用react native在本地存储中保存和检索令牌数据?
这是我的splashscreen.js
import { api } from '../../helpers'
const getAppToken = () => {
const post = {
user: 'dummy',
secret: 'dummy'
}
api.post('/v1/mp/authenticate', post)
.then(res => {
const { Data, Message } = res.data
if (Message === 'SUCCESS') {
setToken('app-token', Data.token)
navigation.replace('MainApp')
}
})
}
const setToken = async (key, value) => {
try {
await AsyncStorage.setItem(key, value)
} catch (error) {
console.log('error')
}
}
useEffect(() => {
getAppToken()
}, [])
这是helpers目录中的api.js
import { axios, AsyncStorage } from '../../libraries'
export const api = axios.create({
baseURL: 'dummy',
headers: {
'X-APP-TOKEN': 'dummy',
'X-Requested-With': 'XMLHttpRequest',
'content-type': 'application/merge -patch+json'
}
})
AsyncStorage.getItem('app-token')
.then(token => {
api.interceptors.request.use(config => {
config.headers = { Authorization: `Bearer${token}` }
return config
}, error => {
console.log(error)
return Promise.reject(error)
})
})
运行api.js文件中的AsyncStorage.getItem(“应用令牌”)时,它会收到401响应
答案 0 :(得分:1)
初始页面屏幕
axios.post('https://your_apikey', {}, {
headers: { 'Authorization': `Basic c2hvcHBpbmdfb2F1dGhfY2xpZW50OnNob3BwaW5nX29hdXRoX3NlY3JldA==` }
}).then(async (response) => {
console.log(response.data.data.access_token);
await AsyncStorage.setItem("token", response.data.data.access_token);
}).catch((error) => {
console.log(error);
});
主页 //我想要的项目(第二个初始页面)
axios.interceptors.request.use(
async config => {
const token = await AsyncStorage.getItem("token")
if (token) {
// console.log('if condition', await AsyncStorage.getItem("token"));
config.headers.Authorization = "Bearer " + token//pass ur token entire app once ur set
} else {
console.log('config');
}
return config
},
error => {
return Promise.reject(error)
}
);
答案 1 :(得分:0)
示例
获取用户数据,然后将令牌设置为本地存储
await login(req)
.then(res => {
this.setState({customerToken: res.token, customerLoading: false});
if (res.token) {
this.setState({customerLoading: true});
AsyncStorage.setItem('customerToken', JSON.stringify(res.token));
let tokenData = {
Authorization: `Bearer ${res.token}`,
};
从本地获取令牌
await AsyncStorage.getItem('customerToken')
.then(ct => {
if (ct !== null) {
// We have data!!
const c_token = JSON.parse(ct);
let tokenData = {
Authorization: `Bearer ${c_token}`,
};