strict-origin-when-cross-origin
后端语言golang
中间件中已经添加了跨域
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// 设置 CORS 中间件
r.Use(Cors())
// 添加路由处理器函数
r.GET("/example", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello, World!",
})
})
r.Run(":8080")
}
// 自定义中间件函数,设置 CORS 响应头
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
// 如果请求方法是 OPTIONS,则直接返回,不再进入下一个处理器函数
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
// 进入下一个处理器函数
c.Next()
}
}
前端也已经设置跨域
import axios from 'axios';
axios.defaults.baseURL = 'http://example.com/api';
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
// 发送 GET 请求
axios.get('/example')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
// 发送 POST 请求
axios.post('/users', {
name: 'John',
age: 30
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
还是不行
这是因为浏览器的安全策略不允许 Access-Control-Allow-Origin
设置*
因此只需修改*
为origin
即可
// Cors 跨域
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin") //请求头部
if origin != "" {
//接收客户端发送的origin (重要!)
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
//服务器支持的所有跨域请求的方法
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
//允许跨域设置可以返回其他子段,可以自定义字段
c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
// 允许浏览器(客户端)可以解析的头部 (重要)
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
//设置缓存时间
c.Header("Access-Control-Max-Age", "172800")
//允许客户端传递校验信息比如 cookie (重要)
c.Header("Access-Control-Allow-Credentials", "true")
}
//允许类型校验
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
}