是的,你可以,我建议使用https://laravel.com/docs/7.x/sanctum而不是护照,因为它更容易设置,而且它是专门为这种情况而创建的。
您需要使用官方 Laravel 包https://github.com/fruitcake/laravel-cors配置 CORS,这样您将打开 Laravel 的 CORS,以便能够从任何 localhost 或您可以设置的任何域访问它allowed_origins。根据包的文档在 cors.php 配置文件中。
在配置 Sanctum/Passport 并确保您使用 Sanctum 或 Passport 文档中描述的方法为您的 SPA 生成所需的令牌createToken后,您必须保存令牌以连接到受保护的端点,但是他们建议使用基于 cookie SPA 的身份验证,但这不是绝对必要。
创建 API 服务
在本例中,我将创建一个 API 服务来封装 API 调用
import axios from 'axios';
const URI = 'https://yourlaravel.api/api/';
axios.defaults.headers.common = { Accept: 'application/json', 'Content-Type': 'application/json' };
const ApiInstance = axios.create();
const API = {
login: (user) => {
return ApiInstance.post(`${URI}login`, user);
},
getUser: () => {
return ApiInstance.get(`${URI}user`);
},
setUser: (user) => {
return ApiInstance.post(`${URI}user`, user);
},
};
向您的登录端点发送登录请求并保存令牌
import API;
API.login({email:'mail@domain.com',password:'32323'})
.then(response=>{
//save the token
//response.data.accessToken
})
使用令牌从受保护的端点获取数据
//Set the default authorization header when you have an access token
axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}
//Get your data
API.getUser().then(response=>{
//response.data
})
//Post something
API.setUser({user:'Os'}).then(response=>{
//response.data
})