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)
          )
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?