在Gorilla Mux中配置CORS:在POST请求中出现403错误 [英] config CORS in Gorilla Mux: 403 error on POST request

查看:191
本文介绍了在Gorilla Mux中配置CORS:在POST请求中出现403错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API,目前正在尝试使用其中一个端点。端点用于POST请求,端点按预期工作。 API在云中运行,我使用 curl 进行了测试,它非常完美,然后从我的反应应用程序中尝试使用它,但是得到 403状态代码



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




$ b $然后,我用一个表单创建了一个简单的HTML文件,在那里我放置了所需的输入,并指向这个端点的动作,它工作得很好。那么,我不知道错误在哪里?我在API中启用了CORS



在我使用Gorilla / mux的API中,我有这样的内容:

  //设置路由器和一些路由
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

我在浏览器中看到的是(西班牙语):


我们在浏览器中输入了以下内容:bpolíticade mismo origen
impide leer el recurso remoto en https:// miURL (razón:falta la
cabecera CORS'Access-Control在英语中:基本上服务器拒绝请求,因为CORS头不存在。


因此,我的路由器配置有什么问题?

有了 rs / cors ,您应该很容易解决CORS问题。



在您的 server.go

 包主

进口(
。 。 。
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 },//只允许获取,只是一个示例
})

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

//绑定到端口8000并通过我们的路由器并通过cors Handler
log.Fatal(http.ListenAndServe(:8000),c.Handler(router)))

fmt.Println(服务器已准备好并正在监听端口:8000。 。)

}

在您的 testhandler.go ,让我们假设你想接受 Content-Type:application / json

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


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:

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?

解决方案

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
}

这篇关于在Gorilla Mux中配置CORS:在POST请求中出现403错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆