在前端,我使用react并通过axios发送请求
import axios from "axios";
import { getToken } from "./auth";
const api = axios.create({
baseURL: import.meta.env.VITE_API_URL,
});
api.interceptors.request.use((config) => {
const token = getToken();
if (token && config && config?.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
export default api;
在后端,我使用的是codeigniter 4。但是当在请求中添加授权承载令牌时,返回cors错误。Access to XMLHttpRequest at 'http://localhost:8080/v1/user' from origin 'http://127.0.0.1:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class Cors implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
$origin = base_api();
header("Access-Control-Allow-Origin: {$origin}");
header("Access-Control-Allow-Headers: X-API-KEY, Origin,X-Requested-With, Content-Type, Accept, Access-Control-Requested-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PATCH, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
die();
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
//
}
}
有没有人遇到过类似的错误?
我到处寻找解决办法,但没有找到。
1条答案
按热度按时间xhv8bpkk1#
我刚刚在React with马克西米利安Schwarzmüller的udemy课程中学习了身份验证,我认为你只需要从客户端分离令牌并检查如下.我不知道如何通过php实现,但希望js实现能帮助你.