golang实现跨域访问的方法

作者:benben_2015 时间:2024-02-15 18:33:31 

前端通过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", "*")
//"*"表示接受任意域名的请求,这个值也可以根据自己需要,设置成不同域名

来源:https://blog.csdn.net/benben_2015/article/details/79247024

标签:golang,跨域
0
投稿

猜你喜欢

  • 讨论闭包传入参数:window & undefined

    2010-05-19 12:55:00
  • Python增强赋值和共享引用注意事项小结

    2023-08-28 01:55:02
  • Mysql数据库实现多字段过滤的方法

    2024-01-16 11:35:48
  • vue项目中安装less依赖的过程

    2024-05-10 14:21:12
  • Python自动化之定位方法大杀器xpath

    2023-11-22 05:08:57
  • Oracle查看和修改连接数(进程/会话/并发等等)

    2024-01-21 15:59:42
  • ORACLE 最大连接数的问题

    2009-07-23 14:27:00
  • MySQL的表级锁,行级锁,排它锁和共享锁

    2024-01-28 15:44:22
  • Python定义函数实现累计求和操作

    2021-07-07 00:54:19
  • 关于JavaScript中的this指向问题总结篇

    2024-04-29 13:21:25
  • tensorflow实现从.ckpt文件中读取任意变量

    2023-01-04 15:39:40
  • js自定义弹框插件的封装

    2024-05-28 15:38:36
  • 详解如何在CentOS7中使用Nginx和PHP7-FPM安装Nextcloud

    2023-11-10 04:55:49
  • Python针对给定列表中元素进行翻转操作的方法分析

    2022-04-19 18:37:07
  • 网页设计标准尺寸参考

    2007-12-29 20:42:00
  • python做翻译软件详解,小白也看得明白

    2023-08-08 06:25:44
  • FrontPage XP设计教程2——网页的编辑

    2008-10-11 12:16:00
  • php封装json通信接口详解及实例

    2023-11-14 21:56:26
  • sql server 2008 忘记sa密码的解决方法

    2024-01-26 22:48:16
  • opencv python在视屏上截图功能的实现

    2021-04-14 04:00:30
  • asp之家 网络编程 m.aspxhome.com