dongtou9934 2018-03-17 15:20
浏览 70

如何使用Java脚本发布json请求并接收对“ go server”(go语言)的json响应

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

I tried this

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();

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)

}

And I am getting a error message

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.

  • 写回答

1条回答 默认 最新

  • duanfu5239 2018-03-17 15:27
    关注

    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)
        }    
    }
    

    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)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?