技术方案
gin + ant + vue
问题
后端已经配置好跨域请求,但是用ant的上传文件代码依然报错
报错信息
Access to XMLHttpRequest at 'http://127.0.0.1:8090/upload' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response.
再一看报错信息,发现虽然前半部分是跨域,但实际问题不是出现在这,
是后端没有允许这一种X-Requested-With
请求头
解决方案
在Access-Control-Allow-Headers
中添加X-Requested-With
代码如下
作为中间件
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, X-Requested-With")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //服务器支持的所有跨域请求的方
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
//放行所有OPTIONS方法
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
// 处理请求
c.Next()
}
}
设置后就可以正常访问了
另外json也会导致跨域请求
解决方法,可以用qs 转一下
onSubmit() {
alert(this.form.name);
alert(this.form.password)
this.$axios.post('/chapter11/tetPostData', qs.stringify({
name: this.form.name,
password: this.form.password,
})).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
},
1 条评论
sfgh · 2022-08-12 22:51
ttttttttttttttttttttttttt
评论已关闭。