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

使用Axum的Rust后端与React前端交互时出现CORS错误如何解决?

Axum + React CORS 请求失败问题解决

问题根源分析

你的问题出在两个关键配置错误上:前端请求头设置不当,以及后端CORS配置未覆盖非简单请求的校验要求。

1. 前端错误添加响应头

你在fetch请求里手动设置了Access-Control-Allow-Origin: *,这个头是后端响应时才需要返回的字段,作用是告诉浏览器允许哪些源访问接口。前端请求时携带这个头完全无效,反而会触发浏览器的CORS检查逻辑异常,直接拦截请求。

2. 后端CORS配置缺少请求头允许

你发送的POST请求使用了Content-Type: application/json,这属于非简单请求,浏览器会先发送OPTIONS预检请求,确认后端是否允许该请求类型和头信息。你的后端CORS配置仅允许了请求方法和源,但未明确允许Content-Type请求头,导致预检请求失败,实际POST请求被浏览器拦截。

修改后的代码

后端(Axum)配置调整

async fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .init();

    let cors = CorsLayer::new()
        .allow_methods([Method::GET, Method::POST, Method::OPTIONS])
        .allow_origin(Any)
        .allow_headers(Any); // 允许所有请求头,也可明确指定Content-Type

    let app = Router::new()
        .route("/", get(hello_world))
        .route("/", post(update_data))
        .layer(cors);

    axum::Server::bind(&"0.0.0.0:5000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

若不想允许所有请求头,可替换为精准配置:

.allow_headers([HeaderName::from_static("content-type")])

前端(React)请求调整

import { Middleware } from 'redux';

const postMiddleware: Middleware = store => next => action => {
  const result = next(action);
  
  fetch('http://192.168.1.50:5000/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      // 移除多余的Access-Control-Allow-Origin头
    },
    body: JSON.stringify({"title": "hello world!"})
  })
  .then(response => {
    console.log('Response:', response);
  })
  .catch(error => {
    console.error('Error:', error);
  });

  return result;
};

export default postMiddleware;

原理补充

  • 简单请求(如GET、POST且Content-Type为application/x-www-form-urlencoded等)不会触发预检;非简单请求必须通过OPTIONS预检后,浏览器才会发送实际请求。
  • Axum的CorsLayer会自动处理OPTIONS请求,但需确保配置包含预检所需的所有允许项(方法、头、源)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:17:52