You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已尝试多种方案仍无法解决Axios请求的CORS跨域错误

解决Axios POST请求的CORS跨域错误

我已花费一整天在Google、Axios文档及YouTube上搜索解决方案,但仍未能解决问题。当我使用axios.post发起请求时,控制台出现如下错误:

Access to XMLHttpRequest at 'http://localhost/prova/test3.php' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

Axios错误详情:

AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
code: "ERR_NETWORK"
config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message: "Network Error"
name: "AxiosError"
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
stack: "AxiosError: Network Error\n    at XMLHttpRequest.handleError (http://localhost:3000/static/js/bundle.js:71536:14)"
[[Prototype]]: Error

已尝试的解决方法

  • 在package.json中配置proxy为http://localhost/,并将axios.post的请求路径改为prova/test3.php,代码如下:

    handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
      event.preventDefault();
    
      const { username, password } = this.state;
    
      axios.post('prova/test3.php', { username, password })
        .then(response => {
          console.log(response.data);
          // handle successful login
        })
        
        .catch(error => {
          console.error(error);
          this.setState({ error: 'Invalid username or password' });
        });
    };
    
  • 在PHP项目文件夹中创建.htaccess文件,内容如下:

    RewriteEngine On
    
    Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ test3.php [L]
    
  • 在PHP文件中添加CORS相关响应头,代码如下:

    <?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET,POST,PUT,OPTIONS");
    header("Access-Control-Allow-Headers:*");
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
      $username = $_POST['username'];
      $password = $_POST['password'];
    ...... some code 
    ?>
    

以上方法均未解决问题,以下是有效的解决方案:

有效解决方案

1. 修正PHP的OPTIONS请求处理与数据解析

浏览器发送非简单POST请求前会触发OPTIONS预请求,需优先处理并终止脚本;同时Axios默认发送JSON格式数据,需用php://input解析(而非$_POST):

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type"); // 明确允许必要请求头,避免通配符潜在问题

// 处理OPTIONS预请求,直接返回200状态码
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 解析JSON格式请求体
    $requestData = json_decode(file_get_contents('php://input'), true);
    $username = $requestData['username'] ?? '';
    $password = $requestData['password'] ?? '';
    // 后续业务逻辑代码
}
?>

2. 修正前端Axios请求路径

package.json的proxy配置要求请求路径以/开头,否则会拼接当前页面路径导致代理失效,修改请求代码:

handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    const { username, password } = this.state;

    axios.post('/prova/test3.php', { username, password }) // 路径前添加/
        .then(response => {
            console.log(response.data);
            // 处理登录成功逻辑
        })
        .catch(error => {
            console.error(error);
            this.setState({ error: 'Invalid username or password' });
        });
};

3. 修复.htaccess配置

将两个RewriteCond规则拆分为单独行,确保路由规则生效:

RewriteEngine On

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ test3.php [L]

4. 排查前端误加的请求头

检查Axios全局配置,确保没有错误添加Access-Control-Allow-Origin请求头(该头属于服务器响应头,不应由前端发送),若存在以下代码请删除:

axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';

内容的提问来源于stack exchange,提问作者DoggoGigga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 05:22:43