如何在标头中添加React Native中方法获取的授权? (后端Laravel)

时间:2019-01-30 00:35:16

标签: javascript reactjs laravel react-native cors

我正在React Native中开发一个应用程序,并在Laravel 5.6中开发一个后端。在React Native方面,我在标题

中发送Authorization时遇到问题

为解决此问题,我尝试了以下解决方案:

  • 在后端设置CORSpackage)并在React Native中添加mode: "cors"mode: "no-cors"选项
  • 在React Native中将credentials: 'include'选项添加到提取方法中
这些解决方案均无效。 :s

反应原生

输出错误

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,它可以工作,但不能在移动应用程序中使用。

0 个答案:

没有答案