当前位置:网站首页>Gin solves cross domain problems
Gin solves cross domain problems
2022-06-11 23:59:00 【. fried eggs with tomatoes】
Why cross domain problems arise
It is no longer a simple request and cross domain , The browser will send OPTIONS Pre inspection request .
Preflighted Requests yes CORS A transparent server authentication mechanism in . The pre check request first needs to send a HTTP OPTIONS Request header , The purpose is to judge whether the actually sent request is secure .
A simple request
A simple request needs to satisfy the following two conditions
- The request method is one of three
- HEAD
- GET
- POST
- HTTP The header information of does not exceed the following fields
- Accept
- Accept Language
- Last-Event-ID
- Content-Type: Limited to (application/x-www-form-urlencoded,multipart/form-data,text/plain)
Complex request
Non simple requests are complex requests
Common complex requests are :
- The request method is PUT or DELETE
- Content-Type Field type is application/json
- Add off core http header
In the case of cross domain , Non simple requests will be initiated once body Of OPTIONS request , be called " preview " request , Used to request permission information from the server , After the pre inspection request is successfully responded , Will launch a real http request .
The pre check request result of the browser can be passed through Access-Control-Max-Age Cache
Problem recurrence
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"> Request data </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(" Request error ") } } ); }); </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")
}




Two times in total /ping request , One return CORS error, once GET The request becomes OPTIONS request , As a result of 404.
The current request is mainly because the front-end re 63342 port , Back end re 8080 Ports form cross domain , also Content-Type Field type is application/json Cross domain problems caused by non simple requests
Solution
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)
}
}
}

边栏推荐
- App startup process: from clicking the application icon to the activity startup process
- Dblink operation in Oracle
- (simple statistics) acwing 3404 Who are your potential friends
- El select drop-down box style combined with El table (pseudo) combined with drop-down selection
- MySQL some simple commands
- [day 7 of JUC learning] reentrantlock and reentrantreadwritelock
- Notes on knowledge points of dynamic planning
- Pleasant and burden free cross process communication
- NFS quotas:Cannot register service: RPC: Authentication error
- Introduction and installation steps of sonarqube
猜你喜欢

多路查找树

Jenkins basic configuration

Top selling commodities 【 project mall 】

Lake Shore—SuperVariTemp 低温恒温器
![[day 7 of JUC learning] reentrantlock and reentrantreadwritelock](/img/44/0ba7f06287734179ee66b8f4990910.png)
[day 7 of JUC learning] reentrantlock and reentrantreadwritelock

2022 618 notebook shopping guide

统一认证中心 Oauth2 高可用坑
![Delete the receiving address [project mall]](/img/3d/60819a1a8c36fd0c1014f91fe80470.png)
Delete the receiving address [project mall]

图及图的遍历

Mingdeyang ADC series development board-ad9653 daughter board multi-channel high resolution and high sampling rate
随机推荐
Mathematical modeling experience ----- summary of three modeling
Oracle uses Navicat tool to import and export data
Graph and graph traversal
04 automatic learning rate - learning notes - lihongyi's in-depth learning 2021
HMS core shows the latest open capabilities in mwc2022, helping developers build high-quality applications
(interval DP | dfs+ memory) acwing 282 Stone merging
oracle中dblink操作
Stm32f103c8t6 related knowledge
(dp) acwing 899. Edit distance
In order to stimulate inspiration and creativity, Shanghai daoning united with XMIND to bring you full-featured mind mapping and brainstorming software
挂载smb共享提示目录无权限
Read 5g RF terminal industry
DOM知识点总结
明德扬FPGA开发板XILINX-K7核心板Kintex7 XC7K325 410T工业级
Single page pull-down refresh and double page pull-down refresh of MUI
Display product details [project mall]
(digital statistics dp+good) acwing 338 Counting problem
Flex flexible layout tutorial and understanding of the main axis cross axis: Grammar
Mingdeyang FPGA development board xilinx-k7 core board kinex7k325 410t industrial grade
Two configurations of data tables in efcore