我正在React Native
中开发一个应用程序,并在Laravel 5.6
中开发一个后端。在React Native方面,我在标题
Authorization
时遇到问题
为解决此问题,我尝试了以下解决方案:
CORS
(package)并在React Native中添加mode: "cors"
和mode: "no-cors"
选项credentials: 'include'
选项添加到提取方法中反应原生
输出错误
statusCode 401
data Object {
"message": "Unauthenticated.",
}
获取方法
export default async ()=> {
const access_token = await AsyncStorage.getItem(ACCESS_TOKEN);
const token_type = await AsyncStorage.getItem(TOKEN_TYPE);
console.log(URL_LOGOUT);
console.log(access_token);
console.log(token_type.concat(' ', access_token));
return fetch(URL_LOGOUT,{
method:'POST',
headers: {
'Accept': 'application/json',
'Authorization': token_type.concat(' ', access_token)
},
})
.then(processResponse)
.then(res => {
const { statusCode, data } = res;
console.log("statusCode",statusCode);
console.log("data",data);
})
.catch( (error) =>{
console.log(error)
});
}
function processResponse(response) {
const statusCode = response.status;
const data = response.json();
return Promise.all([statusCode, data]).then(res => ({
statusCode: res[0],
data: res[1]
}));
}
后端(Laravel)
cors.php
<?php
return [
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedOriginsPatterns' => [],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
];
api.php
Route::middleware(['auth:api','cors'])->group(function () {
...
})
// I added the cors in the $routeMiddleware(Kernel)
我尝试使用Postman,它可以工作,但不能在移动应用程序中使用。