如何使用java脚本发布json请求并从“go服务器”(go语言)接收json响应
我试过这个
JavaScript 代码:
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();
go code:
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)
}
我收到一条错误消息
加载失败http://本地主机:8000/ http://localhost:8000/:对飞行前请求的响应
未通过访问控制检查:无“Access-Control-Allow-Origin”
标头存在于所请求的资源上。原点“空”是
因此不允许访问。
Set Access-Control-Allow-Origin
Golang 代码中的标头以允许请求表单跨源
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)
}
}
您也可以使用 CORS 处理程序API https://github.com/rs/cors对于通过 main 内的路由器的每个请求。
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)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)