【发布时间】:2021-10-16 05:21:25
【问题描述】:
我写了这个控制器的方法
public function login(Request $request)
{
$attr = $request->validate([
'email' => 'required|string|email',
'password' => 'required|string|min:6'
]);
if (!Auth::attempt($attr)) {
return $this->error('Credentials not match', 401);
}
return response()->json([
'access_token' => auth()->user()->createToken('auth_token')->plainTextToken,
'token_type' => 'Bearer',
]);
}
它是返回令牌。但是我怎样才能将这个令牌用于其他请求呢?所以我用 React 写了这段代码 instance.js
import axios from 'axios'
let instance = axios.create({
baseURL: 'http://localhost:8000',
withCredentials: true,
headers: {
'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json',
}
});
export default instance;
Login.js(函数句柄提交)
const handleSubmit = (event) => {
event.preventDefault();
instance.post('/api/auth/login', {
email: emailRef.current.value,
password: passwordRef.current.value
}).then(res => {
instance.get('/api/me').then((response) => {
console.log(response);
}
)
})
}
我发现 withCredentials: true 解决了这个问题并自动在 header 中设置 cookie 的信息。但是当我尝试向 /api/me 发送请求时,我的状态为 401。你能帮帮我吗?
【问题讨论】:
标签: reactjs jwt authorization token laravel-sanctum