2017-09-04 290 views
0

这是我的代码,用于生成将作为cookie进行响应的令牌。如何使用axios发送cookie标记?

public function authenticate(Request $request) 
{ 
    // grab credentials from the request 

    $credentials = ['email'=>$request->header('email'),'password'=>$request->header('password')]; 

    try { 
     // attempt to verify the credentials and create a token for the user 
     if (! $token = JWTAuth::attempt($credentials)) { 
      return response()->json(['error' => 'invalid_credentials'], 401); 
     } 
    } catch (JWTException $e) { 
     // something went wrong whilst attempting to encode the token 
     return response()->json(['error' => 'could_not_create_token'], 500); 
    } 

    return response($token)->cookie(
     'token',$token, 60 
    ); 

} 

而我正在使用axios来处理它。这是我的代码:

axios({ 
     method: 'post', 
     url: 'http://test.dev/authenticate', 
     headers : { 
     'email':'[email protected]', 
     'password':'secret' 
     }, 
     json:true, 
    }) 
axios({ 
     method: 'get', 
     url: 'http://test.dev/api/users', 
     json:true, 
     withCredentials: true 
    }); 

现在,我在如何发送令牌以检索用户列表时遇到问题。我试着添加Credentials:真实但没有运气。

我收到了响应错误token_not_provided。

问题:

  1. 如何从响应中的Cookie标记的值?
  2. 如何使用带有Authorization Bearer {token}的axios发送令牌?

谢谢提前。

+1

不要上传代码图片,如果你想获得帮助上传代码本身的严重镜头!没有人有时间重新键入代码,你可以轻松地复制粘贴 – milo526

回答

0

您需要将令牌添加到您的爱可信标题:

headers: { 
    'Authorization' : 'Bearer ' + token 
} 

确保您存储token一旦你收到它从你的初始授权回来。

+0

嗨,谢谢你的回答。你是什​​么意思存储令牌?我已经将它设置为cookie响应。我还尝试使用response.headers('Set-Cookie')获取令牌值,但结果未定义。 – POGI

相关问题