搜索
首页后端开发GolangCORS 策略:对预检请求的响应未通过访问控制检查:无'Access-Control-Allow-Origin”

CORS 策略:对预检请求的响应未通过访问控制检查:无“Access-Control-Allow-Origin”

问题内容

我在后端使用 golang 和 gin-gonic/gin web 框架,在前端使用 react axios。我已经尝试解决它两天了,但我仍然遇到以下相同的错误:

cors policy: response to preflight request doesn't pass access control check: no 'access-control-allow-origin' header is present on the requested resource.

仅当我尝试发送 patch 请求时才会发生此错误,因此该请求需要预检 options 请求,但 get 和 post 一切都按预期工作,它们不运行任何预检检查。

这是我的路由器配置的代码:

package main

import (
    "book_renting/api"
    "log"
    "net/http"

    "github.com/gin-contrib/sessions"
    "github.com/gin-contrib/sessions/cookie"
    "github.com/gin-gonic/contrib/cors"
    "github.com/gin-gonic/gin"
    _ "github.com/lib/pq"
)

func main() {

    router := gin.default()
    store := cookie.newstore([]byte("your-secret-key"))
    store.options(sessions.options{maxage: 60 * 60 * 24})

    router.use(cors.default())
    router.use(sessions.sessions("sessions", store))

    router.use(func(c *gin.context) {
        host := c.request.header.get("origin")
        c.writer.header().set("access-control-allow-origin", host)
        c.writer.header().set("access-control-allow-credentials", "true")
        c.writer.header().set("access-control-allow-headers", "content-type, authorization")
        c.writer.header().set("access-control-allow-methods", "get, post, put, delete, patch, options")
        if c.request.method == "options" {
            log.println("handling options request")
            c.abortwithstatus(http.statusnocontent)
            return
        }
        log.println("executing cors middleware")
        c.next()
    })

    router.post("/login", api.handlelogin)
    router.get("/logout", api.handlelogout)
    router.post("/register", api.handleregister)
    router.get("/getcookie", api.getcookiesession)

    router.get("/books", api.getbooksapi)
    router.get("/books/:id", api.bookbyidapi)
    router.patch("/rent/:id", api.rentbookapi)
    router.patch("/return/:id", api.returnbookapi)
    router.run("localhost:3000")
}

这是前端:

import axios from 'axios'

const url = 'http://localhost:3000'

export const loginuser = async (credentials) => await axios.post(`${url}/login`, credentials, {withcredentials: true})
export const logoutuser = async () => await axios.get(`${url}/logout`, {withcredentials: true})
export const registeruser = () => axios.post(`${url}/register`)
export const fetchbooks = () => axios.get(`${url}/books`, { withcredentials: true })
export const fetchbookbyid = (book_id) => axios.get(`${url}/books/${book_id}`, { withcredentials: true })
export const rentbook = (book_id) => axios.patch(`${url}/rent/${book_id}`, { withcredentials: true })
export const returnbook = (book_id) => axios.patch(`${url}/return/${book_id}`, { withcredentials: true })

我非常确定我正确设置了后端,它应该返回所有必要的标头。

例如,对于 get 请求,响应标头如下所示:

http/1.1 200 ok
access-control-allow-credentials: true
access-control-allow-headers: content-type, authorization
access-control-allow-methods: get, post, put, delete, patch, options
access-control-allow-origin: http://localhost:3001
content-type: application/json; charset=utf-8
date: sat, 10 jun 2023 22:12:11 gmt
content-length: 495

虽然对于 patch 请求尝试,我没有任何响应(毫不奇怪),并且预检响应标头是:

http/1.1 200 ok
date: sat, 10 jun 2023 22:12:12 gmt
content-length: 0

您对可能出现的问题有什么建议吗?经过这两天我已经毫无头绪了。预先感谢您!

我还尝试添加标题:

c.writer.header().set("access-control-allow-origin", host)
        c.writer.header().set("access-control-allow-credentials", "true")
        c.writer.header().set("access-control-allow-headers", "content-type, authorization")
        c.writer.header().set("access-control-allow-methods", "get, post, put, delete, patch, options")

...再次在 if 语句中:

if c.request.method == "options" {
    log.println("handling options request")
    c.abortwithstatus(http.statusnocontent)
    return
    }

但这根本没有帮助。事实上,这个if语句在执行预检时并没有执行,我从控制台知道服务器正在执行options请求。

[gin] 2023/06/11 - 00:12:13 | 200 |       7.708µs |       127.0.0.1 | options  "/rent/2"

编辑:

这是发送 patch 请求的 curl 命令(因此实际上这是预检 options 请求):

curl 'http://localhost:3000/return/2' \
  -x 'options' \
  -h 'accept: */*' \
  -h 'accept-language: en-us,en;q=0.9,pl-pl;q=0.8,pl;q=0.7' \
  -h 'access-control-request-headers: content-type' \
  -h 'access-control-request-method: patch' \
  -h 'cache-control: no-cache' \
  -h 'connection: keep-alive' \
  -h 'origin: http://localhost:3001' \
  -h 'pragma: no-cache' \
  -h 'referer: http://localhost:3001/' \
  -h 'sec-fetch-dest: empty' \
  -h 'sec-fetch-mode: cors' \
  -h 'sec-fetch-site: same-site' \
  -h 'user-agent: mozilla/5.0 (macintosh; intel mac os x 10_15_7) applewebkit/537.36 (khtml, like gecko) chrome/114.0.0.0 safari/537.36' \
  --compressed

对此请求的响应:

HTTP/1.1 200 OK
Date: Sun, 11 Jun 2023 01:22:57 GMT
Content-Length: 0

正确答案


事实证明,您正在使用已弃用的软件包 github.com/gin-gonic/contrib/cors。您应该使用 github.com/gin-contrib/cors 代替。这是使用 github.com/gin-contrib/cors 的演示配置:

package main

import (
    "github.com/gin-contrib/cors"
    "github.com/gin-contrib/sessions"
    "github.com/gin-contrib/sessions/cookie"
    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.default()

    config := cors.defaultconfig()
    config.addallowheaders("authorization")
    config.allowcredentials = true
    config.allowallorigins = false
    // i think you should whitelist a limited origins instead:
    //  config.allowallorigins = []{"xxxx", "xxxx"}
    config.alloworiginfunc = func(origin string) bool {
        return true
    }
    router.use(cors.new(config))

    store := cookie.newstore([]byte("your-secret-key"))
    store.options(sessions.options{maxage: 60 * 60 * 24})
    router.use(sessions.sessions("sessions", store))

    // routes below

    router.run("localhost:3000")
}

由于某种原因,patch 请求标头缺少“cookie”标头,尽管我使用了 withcredentials 参数。

axios.patch(`${url}/rent/${book_id}`, { withcredentials: true })

这里 { withcredentials: true } 被视为数据,并且没有配置。如果你没有数据发送到服务器,你应该这样写:

axios.patch(`${url}/rent/${book_id}`, null, { withCredentials: true })

以上是CORS 策略:对预检请求的响应未通过访问控制检查:无'Access-Control-Allow-Origin”的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除
Golang行动:现实世界中的示例和应用程序Golang行动:现实世界中的示例和应用程序Apr 12, 2025 am 12:11 AM

Golang在实际应用中表现出色,以简洁、高效和并发性着称。 1)通过Goroutines和Channels实现并发编程,2)利用接口和多态编写灵活代码,3)使用net/http包简化网络编程,4)构建高效并发爬虫,5)通过工具和最佳实践进行调试和优化。

Golang:Go编程语言解释了Golang:Go编程语言解释了Apr 10, 2025 am 11:18 AM

Go语言的核心特性包括垃圾回收、静态链接和并发支持。1.Go语言的并发模型通过goroutine和channel实现高效并发编程。2.接口和多态性通过实现接口方法,使得不同类型可以统一处理。3.基本用法展示了函数定义和调用的高效性。4.高级用法中,切片提供了动态调整大小的强大功能。5.常见错误如竞态条件可以通过gotest-race检测并解决。6.性能优化通过sync.Pool重用对象,减少垃圾回收压力。

Golang的目的:建立高效且可扩展的系统Golang的目的:建立高效且可扩展的系统Apr 09, 2025 pm 05:17 PM

Go语言在构建高效且可扩展的系统中表现出色,其优势包括:1.高性能:编译成机器码,运行速度快;2.并发编程:通过goroutines和channels简化多任务处理;3.简洁性:语法简洁,降低学习和维护成本;4.跨平台:支持跨平台编译,方便部署。

SQL排序中ORDER BY语句结果为何有时看似随机?SQL排序中ORDER BY语句结果为何有时看似随机?Apr 02, 2025 pm 05:24 PM

关于SQL查询结果排序的疑惑学习SQL的过程中,常常会遇到一些令人困惑的问题。最近,笔者在阅读《MICK-SQL基础�...

技术栈收敛是否仅仅是技术栈选型的过程?技术栈收敛是否仅仅是技术栈选型的过程?Apr 02, 2025 pm 05:21 PM

技术栈收敛与技术选型的关系在软件开发中,技术栈的选择和管理是一个非常关键的问题。最近,有读者提出了...

如何在Go语言中使用反射对比并处理三个结构体的差异?如何在Go语言中使用反射对比并处理三个结构体的差异?Apr 02, 2025 pm 05:15 PM

Go语言中如何对比并处理三个结构体在Go语言编程中,有时需要对比两个结构体的差异,并将这些差异应用到第�...

在Go语言中如何查看全局安装的包?在Go语言中如何查看全局安装的包?Apr 02, 2025 pm 05:12 PM

在Go语言中如何查看全局安装的包?在使用Go语言开发过程中,经常会使用go...

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版