当前位置:网站首页>gin解决跨域问题
gin解决跨域问题
2022-06-11 23:56:00 【.番茄炒蛋】
为什么会出现跨域问题
再非简单请求且跨域的情况下,浏览器会发送OPTIONS预检请求.
Preflighted Requests是CORS中一种透明服务器验证机制.预检请求首先需要向另外一个域名的资源发送一个HTTP OPTIONS请求头,其目的就是为了判断实际发送的请求是安全的.
简单请求
简单请求需满足以下两个条件
- 请求方法是以下三种方法之一
- HEAD
- GET
- POST
- HTTP的头信息不超出以下几种字段
- Accept
- Accept Language
- Last-Event-ID
- Content-Type:只限于(application/x-www-form-urlencoded,multipart/form-data,text/plain)
复杂请求
非简单请求即是复杂请求
常见的复杂请求有:
- 请求方法为PUT或DELETE
- Content-Type字段类型为 application/json
- 添加核外的http header
再跨域的情况下,非简单请求会先发起一次空body的OPTIONS请求,称为"预检"请求,用于向服务器请求权限信息,等预检请求被成功响应后,才会发起真正的http请求.
浏览器的预检请求结果可以通过Access-Control-Max-Age进行缓存
问题复现
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<button type="button" id="query">请求数据</button>
<div id="content" style=" width: 300px;height: 500px"></div>
</body>
<script type="text/javascript"> $("#query").click(function () {
$.ajax( {
url:"http://127.0.0.1:8080/ping", dataType: "json", type: "get", contentType:"application/json;charset=utf-8", success: function (result) {
console.log(result.message); $("#content").text(result.message) }, error: function (data) {
alert("请求出错") } } ); }); </script>
</html>
main.go
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}




一共发了两次/ping请求,一次返回CORS error,一次GET请求变成了OPTIONS请求,导致的404.
当前请求主要是因为前端再63342端口,后端再8080端口形成跨域,并且Content-Type字段类型为 application/json为非简单请求造成的跨域问题
解决方案
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.Use(Cors())
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
func Cors() gin.HandlerFunc {
return func(context *gin.Context) {
method := context.Request.Method
context.Header("Access-Control-Allow-Origin", "*")
context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, x-token")
context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PATCH, PUT")
context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
context.Header("Access-Control-Allow-Credentials", "true")
if method == "OPTIONS" {
context.AbortWithStatus(http.StatusNoContent)
}
}
}

边栏推荐
- Mingdeyang FPGA development board xilinx-k7 core board kinex7k325 410t industrial grade
- Shell (32): configure SSH privacy free
- 2022 618笔记本选购指北
- Top selling commodities 【 project mall 】
- SF14 | supertrend "super trend" indicator magic change and upgrade (source code)
- Achievements in science and Technology (XV)
- 图及图的遍历
- How to achieve fair and equitable data access and service ecology?
- [signals and systems] (XXII) Laplace transform and complex frequency domain analysis - s-domain analysis
- Beginner JS BOM implementation window centered
猜你喜欢

愉快无负担的跨进程通信方式

HMS core shows the latest open capabilities in mwc2022, helping developers build high-quality applications

2022 safety officer-a certificate test question simulation test platform operation

chisel环境搭建(win10 + vscode)

HMS core shows the latest open capabilities in mwc2022, helping developers build high-quality applications

oracle使用Navicat工具导入导出数据

Jenkins basic configuration

(dp+ longest common subsequence) acwing 897 Longest common subsequence

SAP SD 创建/修改价格表

Software installation and use, etc
随机推荐
Solr之基礎講解入門
(simple statistics) acwing 3404 Who are your potential friends
Introduction to Solr Basics
oracle使用Navicat工具导入导出数据
挂载smb共享提示目录无权限
Custom JSP tag - > concept - > lifecycle
Integrate工具之Jenkins
【juc学习之路第7天】ReentrantLock与ReentrantReadWriteLock
C language Niuke net string space substitution
loading
Delete the receiving address [project mall]
05 classification learning notes lihongyi's in-depth study 2021
我的创作纪念日
What is webstorage? And cookies
Custom font settings
Solr之基础讲解入门
Dblink operation in Oracle
sonarqube介紹和安裝步驟
Mingdeyang FPGA development board xilinx-k7 core board kinex7k325 410t industrial grade
Lake Shore—SuperVariTemp 低温恒温器