如何发布json请求并接收对“go server”的json响应(去语言)使用Java脚本 [英] How to post a json request and recieve json response to "go server" (go language) using java script

查看:272
本文介绍了如何发布json请求并接收对“go server”的json响应(去语言)使用Java脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用java脚本发布json请求并接收来自go server(去语言)的json响应

How to post a json request and receive json response from "go server" (go language) using java script

我试过了这个

java脚本代码:

java script code:

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)

}

我收到错误讯息

And I am getting a error message


未能加载 http:// localhost:8000 / :对预检请求的响应
未通过访问控制检查:请求的资源上没有Access-Control-Allow-Origin
标题。 Origin'null'是
,因此不允许访问。

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 标题允许请求表单跨越原点

Set Access-Control-Allow-Origin headers in your Golang code to allow request form cross origin

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处理程序来处理每个通过路由器内部的请求。

Also you can use CORS handler using this API for every request passing through router inside your 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)
}

这篇关于如何发布json请求并接收对“go server”的json响应(去语言)使用Java脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆