gpt4 book ai didi

javascript - 如何使用 java 脚本发布 json 请求并接收对 "go server"(go 语言)的 json 响应

转载 作者:数据小太阳 更新时间:2023-10-29 03:42:14 25 4
gpt4 key购买 nike

如何使用 java 脚本发送 json 请求并从“go server”(go 语言)接收 json 响应

我试过了

java脚本代码:

var calculate = { 
operand1 : null,
operand2 : null,
operator : null
};

function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost:8000/", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(calculate);
var response = (xhttp.responseText);
console.log(response);
}
UserAction();

去代码:

package main
import ("fmt"
"net/http"
"encoding/json"
)


type answer struct {
result float64
}


func index(w http.ResponseWriter, r *http.Request) {
ans := answer{result: 30}
fmt.Println(r)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(ans); err != nil {
panic(err)
}
}

func main() {
http.HandleFunc("/",index)
fmt.Println("Server online at port localhost:8000")
http.ListenAndServe(":8000", nil)

}

我收到一条错误消息

Failed to load http://localhost:8000/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

最佳答案

在您的 Golang 代码中设置 Access-Control-Allow-Origin header 以允许跨源请求表单

func index(w http.ResponseWriter, r *http.Request) {
ans := answer{result: 30}
fmt.Println(r)
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(ans); err != nil {
panic(err)
}
}

您还可以使用此 API 来使用 CORS 处理程序对于通过您的主路由器中的每个请求。

func main() {
mux := http.NewServeMux()
mux.HandleFunc("/",index)
handler := cors.Default().Handler(mux)
fmt.Println("Server online at port localhost:8000")
http.ListenAndServe(":8000", handler)
}

关于javascript - 如何使用 java 脚本发布 json 请求并接收对 "go server"(go 语言)的 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49338485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com