登录
首页 >  Golang >  Go问答

处理CORS问题没有获得答复

来源:stackoverflow

时间:2024-03-13 08:45:26 291浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《处理CORS问题没有获得答复》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

我有一个 react 应用程序,使用 fetch 调用 go mux api。

我很清楚这里的问题:让 golang gorilla cors 处理程序工作

但这对我不起作用。我已经尝试了该帖子中的所有内容,但仍然没有成功。看起来 go 甚至没有为我运行任何中间件或路由处理函数。

这是我尝试修复它的第一种方法。这使用 gorilla/handlers

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
)

func commonmiddleware(next http.handler) http.handler {
    return http.handlerfunc(func(w http.responsewriter, r *http.request) {
        fmt.println("middleware called")

        w.header().set("access-control-allow-origin", "*")
        w.header().set("access-control-allow-methods", "post, get, options, put, delete")
        w.header().set("access-control-allow-headers", "accept, content-type, content-length, accept-encoding, x-csrf-token, authorization")

        next.servehttp(w, r)
    })
}

func apihandler(w http.responsewriter, r *http.request) {
    fmt.println("route called")
    fmt.fprintf(w, `{"works:"true}`)
}

func main() {
    var router *mux.router = mux.newrouter()
    router.use(commonmiddleware)

    router.handlefunc("/api", apihandler).methods("post")

    headersok := handlers.allowedheaders([]string{"access-control-allow-origin", "accept", "accept-language", "content-type", "content-language", "origin"})
    originsok := handlers.allowedorigins([]string{"http://localhost:*", "*"})
    methodsok := handlers.allowedmethods([]string{"get", "head", "post", "put", "options"})

    http.listenandserve(":8000", handlers.cors(headersok, originsok, methodsok)(router))
}

这使用 rs/cors

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/rs/cors"
)

func commonmiddleware(next http.handler) http.handler {
    return http.handlerfunc(func(w http.responsewriter, r *http.request) {
        fmt.println("middleware called")
        w.header().set("access-control-allow-origin", "*")
        w.header().set("access-control-allow-methods", "post, get, options, put, delete")
        w.header().set("access-control-allow-headers", "accept, content-type, content-length, accept-encoding, x-csrf-token, authorization")

        next.servehttp(w, r)
    })
}

func apihandler(w http.responsewriter, r *http.request) {
    fmt.println("route called")
    fmt.fprintf(w, `{"works:"true}`)
}

func main() {
    var router *mux.router = mux.newrouter()
    router.use(commonmiddleware)

    router.handlefunc("/api", apihandler).methods("post")

    c := cors.new(cors.options{
        allowedorigins:   []string{"*"},
        allowcredentials: true,
    })

    handler := c.handler(router)

    http.listenandserve(":8000", handler)
}

但是,在这两种情况下,浏览器中仍然会出现 cors 错误。我在端口 5000 上运行 react 服务器,而 go 服务器在端口 8000 上运行。

fetch("http://localhost:8000/api", {
               method: 'post',
               headers: {
                    // "access-control-allow-origin": "*",
                    'content-type': 'application/json'
               },
               body: json.stringify({
                    example: 1
               })
          })

chrome 中的错误:

Access to fetch at 'http://localhost:8000/validate/' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这两种解决方案都不起作用。事实上,go 中的“middleware called”和“route called”永远不会打印出来。 api 在 postman 中工作得很好,所以我知道路由器工作得很好,问题确实是 cors。所以看起来该路由永远不会被调用。

这太令人震惊了,这可能与预检有关。如何禁用所有 cors 问题?


解决方案


如果您想允许所有来源,另一种方法是

c := cors.New(cors.Options{
        AllowOriginFunc: func(r string) bool {
                             return true
                         }
    })

本篇关于《处理CORS问题没有获得答复》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>