【发布时间】:2018-03-18 02:01:55
【问题描述】:
如何使用 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)
}
我收到一条错误消息
无法加载http://localhost:8000/:对预检请求的响应 没有通过访问控制检查:没有“Access-Control-Allow-Origin” 请求的资源上存在标头。原点“空”是 因此不允许访问。
【问题讨论】:
标签: javascript json http go xmlhttprequest