【问题标题】:How to make a clean API call with axios when I need to be authenticated?当我需要进行身份验证时,如何使用 axios 进行干净的 API 调用?
【发布时间】:2019-11-22 05:58:57
【问题描述】:

我正在开发 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

【问题讨论】:

    标签: reactjs api get axios native


    【解决方案1】:

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

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-20
      • 2021-10-16
      • 2023-03-27
      • 2020-04-19
      • 2022-11-08
      • 1970-01-01
      • 2016-08-30
      • 2020-01-21
      • 2019-09-28
      相关资源
      最近更新 更多