Codeigniter 4 RESTful API使用PUT/DELETE方法时出现CORS错误
React + CodeIgniter 4 PUT/DELETE请求CORS错误问题
问题现象
前端基于React框架,通过Axios发送请求;后端使用CodeIgniter 4框架。目前POST和GET请求正常,但发送PUT或DELETE请求时触发CORS错误。Postman测试PUT/DELETE请求可正常响应。
错误提示
Access to XMLHttpRequest at 'http://localhost:8080/v1/finance/1' 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.
Devtools观测情况
- 控制台输出上述CORS拦截错误
- 预检OPTIONS请求返回404状态码
前端代码(React + Axios)
import axios from "axios"; import { getToken } from "./auth"; const api = axios.create({ baseURL: import.meta.env.VITE_API_URL, }); export default api;
后端配置
CodeIgniter 4 CORS过滤器实现
<?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) { // } }
Filters.php全局配置
<?php namespace Config; use CodeIgniter\Config\BaseConfig; use CodeIgniter\Filters\CSRF; use CodeIgniter\Filters\DebugToolbar; use CodeIgniter\Filters\Honeypot; use CodeIgniter\Filters\InvalidChars; use CodeIgniter\Filters\SecureHeaders; use App\Filters\Cors; use App\Filters\AuthFilter; class Filters extends BaseConfig { public $aliases = [ 'csrf' => CSRF::class, 'toolbar' => DebugToolbar::class, 'honeypot' => Honeypot::class, 'invalidchars' => InvalidChars::class, 'secureheaders' => SecureHeaders::class, 'authFilter' => AuthFilter::class, 'cors' => Cors::class, ]; public $globals = [ 'before' => [ 'cors' ], 'after' => [ 'toolbar' ], ]; public $methods = []; public $filters = []; }
.htaccess配置
# Disable directory browsing Options All -Indexes # ---------------------------------------------------------------------- # Rewrite engine # ---------------------------------------------------------------------- # Turning on the rewrite engine is necessary for the following rules and features. # FollowSymLinks must be enabled for this to work. <IfModule mod_rewrite.c> Options +FollowSymlinks RewriteEngine On RewriteCond %{REQUEST_METHOD} OPTIONS RewriteRule ^(.*)$ $1 [R=200,L] #Set headers to access CORS Requests / allowing localhost only Header always add Access-Control-Allow-Origin "*" Header always add Access-Control-Allow-Headers "origin, x-requested-with, content-type" Header always add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS" # If you installed CodeIgniter in a subfolder, you will need to # change the following line to match the subfolder you need. # http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase # RewriteBase / # Redirect Trailing Slashes... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Rewrite "www.example.com -> example.com" RewriteCond %{HTTPS} !=on RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L] # Checks to see if the user is attempting to access a valid file, # such as an image or css document, if this isn't true it sends the # request to the front controller, index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([\s\S]*)$ index.php/$1 [L,NC,QSA] # Ensure Authorization header is passed along RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] </IfModule> <IfModule !mod_rewrite.c> # If we don't have mod_rewrite installed, all 404's # can be sent to index.php, and everything works as normal. ErrorDocument 404 index.php </IfModule> # Disable server signature start ServerSignature Off # Disable server signature end
求助
有没有人遇到过类似问题?找了各种解决方案都没用,修改.htaccess设置Access-Control-Allow-Origin "*"也无效。
内容的提问来源于stack exchange,提问作者Trimander
相关产品推荐
相关产品推荐

