dougao2830 2016-09-20 14:42
浏览 155
已采纳

如何从提取到Go API发出PUT请求?

I am creating a REST API with Go (using Gorilla mux) and a frontend app with React. The GET requests work fine, but I'm having trouble getting the PUT request to work correctly. It makes the OPTIONS preflight request successfully, but never the PUT request. I may be handling it incorrectly on the backend or making the request incorrectly. I'm created a middleware that will add the CORS headers because the gorilla toolkit's CORS handlers weren't allowing the OPTIONS request at all. I have also tried using axios instead of fetch to make sure it wasn't something I was doing incorrectly in the request. I was getting the exact same behavior with axios.

Here is the router:

var V1URLBase string = "/api/v1"

func Load() http.Handler {

    r := mux.NewRouter().StrictSlash(true)

    // Status endpoints
    s := r.PathPrefix(fmt.Sprintf("%s%s", V1URLBase, "/statuses")).Subrouter()

    s.HandleFunc("/", handlers.GetStatuses).
        Methods("GET")
    s.HandleFunc("/{status_id}/", handlers.GetStatus).
        Methods("GET")
    s.HandleFunc("/", handlers.PostStatus).
        Methods("POST")
    s.HandleFunc("/{status_id}/", handlers.PutStatus).
        Methods("PUT")
    s.HandleFunc("/{status_id}/", handlers.DeleteStatus).
        Methods("DELETE")

    // Visit endpoints
    v := r.PathPrefix(fmt.Sprintf("%s%s", V1URLBase, "/visits")).Subrouter()

    v.HandleFunc("/", handlers.GetVisits).
        Methods("GET")
    v.HandleFunc("/{visit_id}/", handlers.GetVisit).
        Methods("GET")
    v.HandleFunc("/", handlers.PostVisit).
        Methods("POST")
    v.HandleFunc("/{visit_id}/", handlers.PutVisit).
        Methods("PUT")
    v.HandleFunc("/{visit_id}/", handlers.DeleteVisit).
        Methods("DELETE")

    // Member endpoints
    m := r.PathPrefix(fmt.Sprintf("%s%s", V1URLBase, "/members")).Subrouter()

    m.HandleFunc("/", handlers.GetMembers).
        Methods("GET")
    m.HandleFunc("/{member_id}/", handlers.GetMember).
        Methods("GET")
    m.HandleFunc("/", handlers.PostMember).
        Methods("POST")
    m.HandleFunc("/{member_id}/", handlers.PutMember).
        Methods("PUT")
    m.HandleFunc("/{member_id}/", handlers.DeleteMember).
        Methods("DELETE")

    // GymLocation endpoints
    gl := r.PathPrefix(fmt.Sprintf("%s%s", V1URLBase, "/gym_locations")).Subrouter()

    gl.HandleFunc("/", handlers.GetGymLocations).
        Methods("GET")
    gl.HandleFunc("/{gym_location_id}/", handlers.GetGymLocation).
        Methods("GET")
    gl.HandleFunc("/", handlers.PostGymLocation).
        Methods("POST")
    gl.HandleFunc("/{gym_location_id}/", handlers.PutGymLocation).
        Methods("PUT")
    gl.HandleFunc("/{gym_location_id}/", handlers.DeleteGymLocation).
        Methods("DELETE")

    router := ghandlers.LoggingHandler(os.Stdout, r)
    router = handlers.WriteCORSHeaders(r)

    return router
}

Here is the CORS handler:

func WriteCORSHeaders(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("HIT")
        w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("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",
        )
        //w.Header().Set("Access-Control-Allow-Credentials", "true")

        if r.Method == "OPTIONS" {
            return
        }

        h.ServeHTTP(w, r)
    })
}

Here is the PUT handler:

func PutVisit(w http.ResponseWriter, r *http.Request) {
    body, _ := ioutil.ReadAll(r.Body)
    r.Body.Close()

    visitId, err := strconv.ParseInt(mux.Vars(r)[VisitId], 10, 64)
    if err != nil {
        WriteJSON(w, http.StatusBadRequest, APIErrorMessage{Message: InvalidVisitId})
        return
    }

    visit := &models.Visit{}
    err = json.Unmarshal(body, visit)
    if err != nil {
        WriteJSON(w, http.StatusBadRequest, APIErrorMessage{Message: err.Error()})
        return
    }

    updated, err := datastore.UpdateVisit(visitId, *visit)
    if err != nil {
        WriteJSON(w, http.StatusInternalServerError, APIErrorMessage{Message: err.Error()})
        return
    }

    WriteJSON(w, http.StatusOK, updated)
}

func WriteJSON(w http.ResponseWriter, statusCode int, response interface{}) {
    encoder := json.NewEncoder(w)
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    w.WriteHeader(statusCode)
    encoder.Encode(response)
}

Here is the main that starts the server:

func main() {
    r := router.Load()

    http.ListenAndServe(":8080", r)
}

Here is my request from Reactjs:

export function putVisit(visit) {
  return function(dispatch) {
    return fetch(`http://localhost:8080/api/v1/visits/${visit.visit_id}/`, {
      method: 'PUT',
      headers: {
        'Accept': 'application/json; charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(visit)
    })
      .then(response => response.json())
      .then(json =>
        dispatch(updateVisit(json))
      )
      .catch(err =>
        console.log(err)
      )
  }
}
  • 写回答

1条回答 默认 最新

  • douhengdao4499 2016-09-20 20:13
    关注

    In case someone else comes across a similar issue, I was able to get this working by adding the JSON header to my CORS function(instead of the WriteJSON function) like this:

    func CORS(h http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            w.Header().Set("Content-Type", "application/json; charset=UTF-8")
            w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("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",
            )
            w.Header().Set("Access-Control-Allow-Credentials", "true")
    
            if r.Method == "OPTIONS" {
                return
            }
            h.ServeHTTP(w, r)
        })
    }
    

    After I added that, the request was still not working with fetch. So, I switched tried it with axios again and it worked. Here is what the new request code looks like with axios.

    export function putVisit(visit) {
      return function(dispatch) {
        return axios.put(`http://localhost:8080/api/v1/visits/${visit.visit_id}/`, visit)
          .then(response =>
            dispatch(updateVisit(response.data))
          )
          .catch(err =>
            console.log(err)
          )
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码