需要身份验证时,如何使用axios进行干净的API调用?

时间:2019-07-12 12:54:30

标签: reactjs api get axios native

我正在使用React Native,并且必须调用同事创建的API。我已经成功进行了POST调用以进行身份​​验证,我拥有访问令牌(即使我不知道它是否有用..)和用户的ID。现在,我想进行一次GET调用以获取用户的数据,但是我被困在这里。

登录路径为:

Route::post('users/auth/login', function(Request $request) {

$data = $request->validate([
    'email' => 'required|email',
    'password' => 'required|string',
]);

$user = User::whereEmail($data['email'])->firstorFail();

if ($user) {
    if (!Hash::check($data['password'], $user->password)) {
        return response()->json(['error' => 'Invalid credentials'], 401);
    }

    $tokenResult = $user->createToken('Personal Access Token');
    $token = $tokenResult->token;
    $token->expires_at = Carbon::now()->addWeeks(1);
    $token->save();

    return response()->json([
    'access_token' => $tokenResult->accessToken,
    'token_type' => 'Bearer',
    'expires_at' => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString(),
    'user' => $user,
    ]);
}

});

用户的数据路由为:

Route::middleware('auth:api')->group(function () {

//Infos de l'Utilisateur connecté
Route::get('users/info', function () {
    return(User::where('id', Auth::id())->firstorFail());
});
}

这可以进行身份​​验证:

axios.post("http://1.xx.xx.4:81/api/users/auth/login", {
    email: email,
    password: pass,
  },)
  .then((response) => {
     deviceStorage.saveItem("access_token", response.data.access_token);
     deviceStorage.saveItem("idUser", toString(response.data.user.id));
     this.newJWT(response.data.access_token);
     this.newJWT(response.data.user.id);
     this.setState({id: response.data.user.id});
     console.log("Connexion done.\n" + response + "\nUser's name = " + response.data.user.name + "\nUser's id = " + response.data.user.id);
}

我尝试过这样的事情:

    axios.get('http://1.xx.xx.4:81/api/users/info')
      .then(function (response) {
          // handle success
      console.log("API done");
          console.log(response);
      })
      .catch(function (error) {
          // handle error
      console.log("API failed");
          console.log(error);
      })
      .finally(function () {
          // always executed
      console.log("API always");
      });

我也尝试过在“标头”中使用参数,但没有任何效果...

尝试获取数据时出现此错误:

Request failed with status code 401
- node_modules\axios\lib\core\createError.js:16:24 in createError
- node_modules\axios\lib\core\settle.js:18:6 in settle
- node_modules\axios\lib\adapters\xhr.js:59:13 in handleLoad
- node_modules\event-target-shim\lib\event-target.js:172:43 in     dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:570:23 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:392:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter  \EventEmitter.js:191:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:349:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:106:26 in <unknown>
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:297:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:105:17 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue

2 个答案:

答案 0 :(得分:0)

您将需要发送承载令牌,通常将401状态与端点错误相关联,这是因为尝试通过get请求获取数据时未提供访问令牌。

const token = deviceStorage.getItem("access_token");

const config = {
  headers: {'Authorization': "bearer " + token}
};


axios.get('http://192.168.1.250:81/api/users/info', config)
      .then(function (response) {
          // handle success
      console.log("API done");
          console.log(response);
      })
      .catch(function (error) {
          // handle error
      console.log("API failed");
          console.log(error);
      })
      .finally(function () {
          // always executed
      console.log("API always");
      });


// Other work around using template literal

const token = deviceStorage.getItem("access_token");

axios.get('http://192.168.1.250:81/api/users/info', { headers: {"Authorization" : `Bearer ${token}`} })
      .then(function (response) {
          // handle success
      console.log("API done");
          console.log(response);
      })
      .catch(function (error) {
          // handle error
      console.log("API failed");
          console.log(error);
      })
      .finally(function () {
          // always executed
      console.log("API always");
      });

答案 1 :(得分:0)

我要做的是,当用户登录时,您在 axios 中设置了全局 Authorization 标头,因此您所有的请求都具有令牌,我在索引中执行了此操作,因此在每个查看标头配置已更新:

const _token = window.localStorage.getItem( 'token' );

if( userIsLogged ){
  axios.defaults.headers.common['Authorization'] = `Bearer ${ _token }`;
}
else {
// Your action if is not logged.
// I just remove localStorage Items
}