doujieyu7062 2015-07-14 16:36 采纳率: 0%
浏览 237
已采纳

Golang中HTTP POST的预检问题

I am using mux package and have this code:

func saveConfig(w http.ResponseWriter, r *http.Request) {
    if origin := r.Header.Get("Origin"); origin != "" {
        w.Header().Set("Access-Control-Allow-Origin", origin)
        fmt.Println("Origin: " + 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")
    }
    // Stop here if its Preflighted OPTIONS request
    if r.Method == "OPTIONS" {
        return
    }

    body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
    if err != nil {
        fmt.Println("Error: %s
", err)
        w.WriteHeader(http.StatusInternalServerError)
        return
    }

    fmt.Println("JSON body:" + string(body))
    if err := r.Body.Close(); err != nil {
        panic(err)
    }

    w.WriteHeader(http.StatusCreated)
}

It's working fine on IE but chrome preflight is sending an OPTIONS method and I am getting 404 response back. Any help would be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • du521521521 2015-07-14 17:40
    关注

    The code registers for POST, but not OPTIONS. One approach is to change your code to the following:

    func NewRouter() *mux.Router { 
        router := mux.NewRouter().StrictSlash(true) 
        for _, route := range routes { 
            var handler http.Handler 
            handler = route.HandlerFunc
            handler = commonlibrary.Logger(handler, route.Name) 
            return router.Methods(route.Method, "OPTIONS").Path(route.Pattern).Name(route.Name).Handler(handler)
     }
    

    This will add OPTIONS to all handlers. Another approach is to change the Route Method field to Methods []string and create the router as:

    return router.Methods(route.Methods..., "OPTIONS").Path(route.Pattern).Name(route.Name).Handler(handler)
    

    This will allow you to add OPTIONS to a subset of the handlers.

    Yet another approach is to register a separate handler for OPTIONS:

     Route{"saveConfig", "OPTIONS", "/saveConfig", preflight}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流