如何用JavaScript向Go语言服务器发送JSON请求并接收响应
解决JS向Go服务器发送JSON请求并接收响应的问题
嘿,我来帮你搞定这个JavaScript和Go的JSON交互问题!先看看你的现有代码里的小问题,再把Go服务器的代码补全,让整个流程跑起来~
一、修正你的JavaScript代码
你的JS代码有两个关键问题需要调整:
- 发送请求时,直接传
calculate对象是不行的,必须把它转换成JSON字符串(用JSON.stringify()) - 因为你用的是异步请求(
open的第三个参数是true),不能在send()之后立刻获取responseText,得等请求完成后在onload回调里处理响应
修正后的完整JS代码:
// 先给测试值,不然都是null没法计算 var calculate = { operand1: 10, operand2: 5, operator: "+" }; function UserAction() { var xhttp = new XMLHttpRequest(); // 监听请求成功完成的事件 xhttp.onload = function() { // 先判断请求状态是否正常 if (this.status >= 200 && this.status < 300) { // 把服务器返回的JSON字符串解析成对象 var response = JSON.parse(this.responseText); console.log("服务器响应结果:", response); } else { console.error("请求出错,状态码:", this.status); } }; // 监听网络错误事件 xhttp.onerror = function() { console.error("请求发生网络错误,请检查服务器是否启动"); }; xhttp.open("POST", "http://localhost:8000/", true); xhttp.setRequestHeader("Content-type", "application/json"); // 将JS对象转为JSON字符串后发送 xhttp.send(JSON.stringify(calculate)); } UserAction();
二、补全Go服务器代码
你的Go代码只写了开头,我帮你补全完整的服务端逻辑,包括接收JSON请求、处理计算、返回JSON响应,还加了跨域处理(避免前端报错):
package main import ( "encoding/json" "log" "net/http" ) // 定义和前端请求对应的结构体,JSON标签要和JS里的键名完全一致 type CalculateRequest struct { Operand1 float64 `json:"operand1"` Operand2 float64 `json:"operand2"` Operator string `json:"operator"` } // 定义服务器返回的响应结构体 type CalculateResponse struct { Result float64 `json:"result"` Error string `json:"error,omitempty"` // omitempty表示如果Error为空,就不返回这个字段 } // 处理请求的核心handler func calculateHandler(w http.ResponseWriter, r *http.Request) { // 只允许POST请求 if r.Method != http.MethodPost { http.Error(w, "仅支持POST请求", http.StatusMethodNotAllowed) return } // 设置CORS响应头,允许本地前端访问(开发环境用*,生产环境要指定具体域名) w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST") w.Header().Set("Access-Control-Allow-Headers", "Content-Type") // 解析前端发送的JSON请求体 var req CalculateRequest err := json.NewDecoder(r.Body).Decode(&req) if err != nil { http.Error(w, "解析请求失败:"+err.Error(), http.StatusBadRequest) return } defer r.Body.Close() // 记得关闭请求体 // 执行计算逻辑 var resp CalculateResponse switch req.Operator { case "+": resp.Result = req.Operand1 + req.Operand2 case "-": resp.Result = req.Operand1 - req.Operand2 case "*": resp.Result = req.Operand1 * req.Operand2 case "/": if req.Operand2 == 0 { resp.Error = "除数不能为0" } else { resp.Result = req.Operand1 / req.Operand2 } default: resp.Error = "不支持的运算符:" + req.Operator } // 设置响应头为JSON格式 w.Header().Set("Content-Type", "application/json") // 将响应结构体转为JSON发送给前端 err = json.NewEncoder(w).Encode(resp) if err != nil { log.Printf("发送响应失败:%v", err) http.Error(w, "服务器内部错误", http.StatusInternalServerError) } } func main() { // 注册请求路由 http.HandleFunc("/", calculateHandler) log.Println("服务器已启动,监听地址:http://localhost:8000/") // 启动服务器,监听8000端口 log.Fatal(http.ListenAndServe(":8000", nil)) }
三、运行步骤
- 把Go代码保存为
main.go,然后在终端运行:go run main.go,服务器就会启动在8000端口 - 把修正后的JS代码放到HTML文件里,或者直接在浏览器控制台运行
UserAction(),就能看到服务器返回的计算结果啦!
内容的提问来源于stack exchange,提问作者akash sc
相关产品推荐
相关产品推荐

