dongshang3309 2018-08-11 16:01
浏览 138
已采纳

使用fetch()将jQuery.ajax()替换为Go REST API端点-空有效负载

I currently have a ReactJS web application that creates a POST or PUT request to a REST API endpoint. The REST API is built with golang.

Everything works fine when I use jQuery to make the Ajax POST request. Here's a demonstration of the code:

// my jquery attempt

let sendUrl = "http://192.168.11.241:8000/user";
let sendType = "POST";

let data = {"userid":1};
const postData = [{name:"data",value:JSON.stringify(data)}];

let result = $.ajax({
  type: "POST",
  dataType: 'json',
  cache: false,
  url: sendUrl,
  data: postData
});

And here's what my REST API code looks like

// main.go
package main

import (
  "user"
  "github.com/gorilla/mux"
  "log"
  "net/http"
)

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/payment/{payment_type}", user.Post).Methods("POST","OPTIONS")
     log.Fatal(http.ListenAndServe(":8000", router))
}

// user.go
func Post(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Access-Control-Allow-Origin", "*")
  w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  url := mux.Vars(r)
  r.ParseForm()
  qs := r.Form
  fmt.Println(qs)
}

When I run the JS and Go API code, I successfully see the userid 1 content output to bash.

Now I replace my javascript code with fetch call like this:

let sendUrl = "http://192.168.11.241:8000/user";
let sendType = "POST";

let data = {"userid":1};
const postData = [{name:"data",value:JSON.stringify(data)}];

fetch(sendUrl, {
  method: "POST",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  //body: JSON.stringify(postData)
  body: {"data":JSON.stringify(data)}
});

My Go API acknowledges a POST request is being made, but the post data is empty and I don't see the userid 1. I tried different types of input for the body like with and without json.stringify, I tried different header information like 'Content-Type': 'application/x-www-form-urlencoded', or removing the headers all together, but the data continues to be empty when receiving with my go api.

Anyone know what I'm doing wrong?

  • 写回答

2条回答 默认 最新

  • drflkphi675447 2018-08-11 16:12
    关注

    Ok, I found the right combination of settings for my fetch() call to be this:

    let sendUrl = "http://192.168.11.241:8000/user";
    let sendType = "POST";
    
    let data = {"userid":1};
    const postData = "data="+JSON.stringify(data);
    fetch(sendUrl, {
      method: "POST",
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: postData
    });
    

    I had to re-work the structure of my postData object and also change the content-type

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵