【发布时间】:2020-10-10 12:08:26
【问题描述】:
我是 React Native 和 Axios 的新手,我正在尝试构建一个身份验证系统,我的 API(在 Laravel 中创建)在 Postman 中运行良好,当我来测试整个应用程序并尝试登录时,我得到了这个错误:
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'error.response.data')]
* src\AuthProvider.js:36:36 in axios.post.then._catch$argument_0
- node_modules\react-native\node_modules\promise\setimmediate\core.js:37:13 in tryCallOne
- node_modules\react-native\node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:181:14 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:441:30 in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:387:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:4 in flushedQueue
* [native code]:null in flushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
我正在使用我的安卓手机进行测试,这里是可能的代码:
axios.defaults.baseURL = 'http://localhost:8000';
export const AuthContext = React.createContext({});
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
return (
<AuthContext.Provider
value={{
user,
setUser,
error,
setError,
login: (email, password) => {
axios.post('/api/sanctum/token', {
email,
password,
device_name: 'mobile',
})
.then(response => {
const userResponse = {
email: response.data.user.email,
token: response.data.token,
};
setUser(userResponse);
SecureStore.setItemAsync('user', JSON.stringify(userResponse));
})
.catch(error => {
// const key = Object.keys(error.response.data.errors)[0];
// setError(error.response.data.errors[key][0]);
console.log(error);
});
},
logout: () => {
axios.defaults.headers.common['Authorization'] = `Bearer ${user.token}`;
axios.post('/api/logout')
.then(response => {
setUser(null);
SecureStore.deleteItemAsync('user');
})
.catch(error => {
console.log(error.response);
});
}
}}>
{children}
</AuthContext.Provider>
);
}
【问题讨论】:
标签: laravel react-native axios