我是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
我正在使用我的Android手机进行测试,以下可能是代码:
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>
);
}
答案 0 :(得分:0)
如果您使用的是Android设备,请尝试通过https://cloud.google.com/endpoints/docs/grpc/service-account-authentication#set_up_authentication_in_the_grpc_api_configuration更改localhost,如果尝试使用电话浏览器访问Laravel项目,则会看到您将无法访问默认项目欢迎,但是只要更改它,便可以。
答案 1 :(得分:0)
已经解决。
我使用了ngrok
。它正在生成一个自定义url
来用于Android设备。