golang实现跨域访问

栏目: JavaScript · 发布时间: 6年前

内容简介:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/benben_2015/article/details/79247024

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/benben_2015/article/details/79247024

前端通过Ajax来获取服务器资源时,会存在跨域问题。因为Ajax只能同源使用(预防某些恶意行为),所以当访问不在同一个域中的资源时,就会出现跨域限制。尤其在开发和测试时,跨域问题会给前端测试带来非常不便。

不过CORS(Cross-Origin Resource Sharing,跨域资源共享)解决了这个问题,它背后的基本思想是:使用自定义的HTTP头部让浏览器与服务器进行沟通,从而决定请求或响应是否应该成功。CORS需要浏览器和服务器同时支持。整个CORS通信过程,浏览器是自动完成,而服务器需要手动配置。

ajax.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script>
        function loadXMLDoc() {
            var xmlhttp;
            if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
            }
            else {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", "http://127.0.0.1:8000/ajax", true);
            xmlhttp.send();
        }
    </script>
    <title>Document</title>
</head>
<body>
    <h2>cross origin</h2>
    <button type="button" onclick="loadXMLDoc()">请求数据</button>
    <div id="myDiv"></div>
</body>
</html>

crossorigin.go

package main

import (
    "net/http"
    "html/template"
    "fmt"
    "encoding/json"
)

type Message struct {
    Name string `json:"name"`
    Msg  string `json:"msg"`
}

func main() {
    http.HandleFunc("/", Entrance)
    http.HandleFunc("/ajax", TestCrossOrigin)
    http.ListenAndServe(":8000", nil)
}

func Entrance(w http.ResponseWriter, r *http.Request) {
    t,_:=template.ParseFiles("templates/ajax.html")
    t.Execute(w, nil)
}

func TestCrossOrigin(w http.ResponseWriter, r *http.Request) {
    if r.Method == "GET" {
        var message Message
        message.Name = "benben_2015"
        message.Msg = "success"

        result, err := json.Marshal(message)
        if err != nil {
            fmt.Println(err)
            return
        }
        ResponseWithOrigin(w, r, http.StatusOK, result)
        return
    }
}
func ResponseWithOrigin(w http.ResponseWriter, r *http.Request, code int, json []byte) {
    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    w.WriteHeader(code)
    w.Write(json)
}

当从 http://localhost:8000/ 页面(ajax.html)通过ajax访问 http://localhost:8000/ajax 时,就会出现下图所示的错误:

golang实现跨域访问 解决方法: golang设置HTTP头部相当简单,标准包有现成的方法可以使用。只要在服务器端的响应头中添加下面一句代码就可以正常访问了。

w.Header().Set("Access-Control-Allow-Origin", "*")
//"*"表示接受任意域名的请求,这个值也可以根据自己需要,设置成不同域名

以上所述就是小编给大家介绍的《golang实现跨域访问》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Python Data Structures and Algorithms

Python Data Structures and Algorithms

Benjamin Baka / Packt Publishing / 2017-5-30 / USD 44.99

Key Features A step by step guide, which will provide you with a thorough discussion on the analysis and design of fundamental Python data structures.Get a better understanding of advanced Python c......一起来看看 《Python Data Structures and Algorithms》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具