在Gorilla Mux中配置CORS:在POST请求上出现403错误。

huangapple go评论93阅读模式
英文:

config CORS in Gorilla Mux: 403 error on POST request

问题

我有一个API,目前正在尝试使用其中一个端点。该端点用于处理POST请求,端点按预期工作。API正在云中运行,我使用curl进行了测试,结果完美无误,但是从我的React应用程序中尝试使用它时,我收到了403状态码

在浏览器的控制台中观察,我发现我在OPTIONS请求上收到了该错误,并且POST请求从未完成。下面是控制台中显示的结果的屏幕截图:

在Gorilla Mux中配置CORS:在POST请求上出现403错误。

然后,我创建了一个简单的HTML文件,其中包含所需的输入,并将操作指向此端点,结果运行得很好。然后,我不知道错误可能出在哪里?我已经在API中启用了CORS。

在API中,我使用了Gorilla/mux,并且代码如下:

// 设置路由和一些路由处理函数
	r := mux.NewRouter()
	r.HandleFunc("/", handleHome)
	// 其他一些路由

	headersOk := handlers.AllowedHeaders([]string{"*"})
	originsOk := handlers.AllowedOrigins([]string{"*"})
	methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

	// 启动HTTP服务器
	port := fmt.Sprintf(":%d", SomePort)
	http.ListenAndServe(port, handlers.CORS(originsOk, headersOk, methodsOk)(r))

使用的库有:

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

我在浏览器中收到的消息是(用西班牙语):

> Solicitud desde otro origen bloqueada: la política de mismo origen
> impide leer el recurso remoto en https://miURL (razón: falta la
> cabecera CORS 'Access-Control-Allow-Origin').

翻译成英文就是:基本上,服务器拒绝了请求,因为缺少CORS头。

那么,在我的路由器配置中我做错了什么?

英文:

I have an API, currently am trying to consume one of its endpoints. The endpoint is for POST requests, the endpoint is working as expected. The API is running in the cloud, I tested it with curl and it was perfect, then from my react app I was trying to consume it but I get 403 status code.

Watching in the console of the browser I see that I get that error on a OPTIONS request, and the POST never get done. Here is a screenshot of the result displayed in the console:

在Gorilla Mux中配置CORS:在POST请求上出现403错误。

Then, I made a simple HTML file with a form, there I placed the required inputs, and the action pointing to this endpoint and it worked pretty well. Then, I don't know where would be the error? I have enabled CORS in the API

In the API I am using Gorilla/mux and I have something like this:

// Set up a router and some routes
	r := mux.NewRouter()
	r.HandleFunc("/", handleHome)
	//some other routes

	headersOk := handlers.AllowedHeaders([]string{"*"})
	originsOk := handlers.AllowedOrigins([]string{"*"})
	methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

	// Start http server
	port := fmt.Sprintf(":%d", SomePort)
	http.ListenAndServe(port, handlers.CORS(originsOk, headersOk, methodsOk)(r))

Using:

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

The message that I am getting in the browser is (in Spanish):

> Solicitud desde otro origen bloqueada: la política de mismo origen
> impide leer el recurso remoto en https://miURL (razón: falta la
> cabecera CORS 'Access-Control-Allow-Origin').

In English: basically the server is rejecting the request because the CORS header is not present.

So, what have I done wrong in my router configuration?

答案1

得分: 8

使用rs/cors,您可以轻松解决CORS问题。

在您的server.go文件中:

package main

import (
    . . .       
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/mux"
    "github.com/rs/cors"
    "../myhandler"
)

func main() {
    fmt.Println("设置服务器,启用CORS. . .")

    c := cors.New(cors.Options{
        AllowedOrigins: []string{"*"}, // 允许所有来源
        AllowedMethods: []string{"GET"}, // 仅允许GET请求,这只是一个示例
    })

    router := mux.NewRouter()
    // 示例处理程序
    router.HandleFunc("/test", myhandler.TestHandler())
    http.Handle("/", router)

    // 绑定到端口8000,并传递我们的路由器和cors处理程序
    log.Fatal(http.ListenAndServe(":8000", c.Handler(router)))

    fmt.Println("服务器已准备就绪,正在监听端口:8000. . .")
}

在您的testhandler.go文件中,假设您希望接受Content-Type: application/json

. . .

func TestHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    return
}
英文:

With rs/cors you should solve CORS issues pretty easily.

On your server.go

package main

import (
    . . .       
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/mux"
    "github.com/rs/cors"
    "../myhandler"
)

func main() {

fmt.Println("Settin up server, enabling CORS . . .")

  c := cors.New(cors.Options{
	  AllowedOrigins: []string{"*"}, // All origins
	  AllowedMethods: []string{"GET"}, // Allowing only get, just an example
  })

  router := mux.NewRouter()
  // Example handler
  router.HandleFunc("/test", myhandler.TestHandler())
  http.Handle("/", router)

  // Bind to port 8000 and pass our router in and pass the cors Handler
  log.Fatal(http.ListenAndServe(":8000"), c.Handler(router)))

  fmt.Println("Server is ready and is listening at port :8000 . . .")

}

And on your testhandler.go, let's suppose you want to accept Content-Type: application/json

. . .

func TestHandler func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
	return
}

huangapple
  • 本文由 发表于 2017年8月31日 00:47:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/45965812.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定