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

Go+React项目POST请求CORS报错求助:预检请求未通过校验

Go后端+React前端POST请求CORS错误解决方法

问题分析

你的POST请求触发CORS错误,核心原因有两个:前端请求头冗余,后端CORS配置重复冲突导致预请求(OPTIONS)响应不符合浏览器要求。

修复步骤

1. 移除前端无效请求头

前端请求中添加Access-Control-Allow-Origin是错误的,这个头是后端响应时返回的,前端无需设置。修改saveCards函数:

const EditDeckRoute = ({deckNames, deckID}) => {
    const url = "http://localhost:8080/api/deck/" + deckID
    const [deckInfo, setDeckInfo] = React.useState([])

    React.useEffect(() => {
        axios.get(url).then((response) => {
            setDeckInfo(response.data)
        })
    }, [url])
    
    function saveCards() {
        // 移除多余的Access-Control-Allow-Origin请求头
        axios.post(url, deckInfo, { params:{"deckName": deckNames.get(deckID)}})
    }

    return (
        <>
            <div className="wrapper">
                <div className="header">
                    <h1>Edit Flashcards</h1>
                    <button onClick={saveCards} >Save Cards</button>
                </div>
            </div>
            <div id="detail">
                <Outlet />
            </div>
        </>
    )
}

2. 修复后端CORS配置冲突

你同时使用了自定义corsMiddleware和gorilla/handlers的CORS中间件,两者重复处理CORS逻辑,导致OPTIONS预请求响应头异常。保留gorilla/handlers的配置即可,它能更规范地处理CORS:

package main

import (
    "log"
    "net/http"
    "os"

    "github.com/GrantCanty/flashcards/routes"
    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
)

func main() {
    ctx := routes.NewAppContext()
    r := mux.NewRouter()

    r.HandleFunc("/api/decks", ctx.GetDeckTitles()).Methods("GET")
    r.HandleFunc("/api/deck/{id}", ctx.GetDeck()).Methods("GET")
    r.HandleFunc("/api/deck/{id}", ctx.AddDeck()).Methods("POST")
    r.HandleFunc("/api/deckcount", ctx.GetDeckLength()).Methods("GET")
    r.HandleFunc("/api/user", ctx.GetProfileData()).Methods("GET")

    // 统一配置CORS,覆盖所有必要的请求头和方法
    corsOptions := handlers.CORS(
        handlers.AllowedOrigins([]string{os.Getenv("ORIGIN_ALLOWED")}),
        handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"}),
        handlers.AllowedHeaders([]string{"Content-Type", "AccessToken", "X-CSRF-Token", "Authorization", "Token", "X-Requested-With"}),
        handlers.AllowCredentials(),
    )

    log.Fatal(http.ListenAndServe(":8080", corsOptions(r)))
}

关键注意点

  • 确保环境变量ORIGIN_ALLOWED设置为http://localhost:3000,本地测试时也可以直接写死该值,避免环境变量未配置的问题。
  • OPTIONS预请求是浏览器自动发送的,后端必须正确响应并返回所需的CORS头,gorilla/handlers会自动处理OPTIONS请求,无需手动编写逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:27:22