如何解决Vue + Golang:从源头访问 [Apiurl] 处的 XMLHttpRequest 已被 CORS 策略阻止:不允许请求头字段授权
我是 Vuejs 和 golang 的初学者。 在从 vue axios 调用 api 时尝试通过标头发送授权令牌时出现以下错误。
从源 'http://localhost:5500' 访问 XMLHttpRequest at 'http://localhost:5000/greet/hello' 已被 CORS 策略阻止:Access-Control 不允许请求标头字段授权-预检响应中的 Allow-Headers。
[实际上我在另一个项目中出错了。但是为了理解解决方案,我在简单的以下项目中实现了这个。所以任何人都可以在他们的最后测试代码并提供解决方案]
App.go
package main
import (
"fmt"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.Use(cors.Default())
router.Use(Authenticate())
v1 := router.Group("/greet")
{
v1.POST("/hello",handleFunc)
}
router.Run(":5000")
}
func handleFunc(c *gin.Context) {
var student struct {
Name string `json:"name"`
}
if c.BindJSON(&student) != nil {
c.JSON(400,gin.H{"message": "Provide required details."})
c.Abort()
return
}
message := fmt.Sprintf("%s%s","Good Morning ",student.Name)
c.JSON(200,gin.H{"message": message})
}
func Authenticate() gin.HandlerFunc {
return func(c *gin.Context) {
requiredToken := c.Request.Header["Authorization"]
if len(requiredToken) == 0 {
c.JSON(400,gin.H{"message": "No token found"})
c.Abort()
return
}
fmt.Println(requiredToken)
c.Next()
}
}
index.html
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
</head>
<body>
<div id="app" class="container m-5">
<p>{{name}}</p>
<input type="text" class="form-control col-3" placeholder="Enter Name" v-model="name"/><br>
<button @click="onButtonClick" class="btn btn-info">CALL API</button>
</div>
<script src="index.js"></script>
</body>
</html>
index.js
var app = new Vue({
el: '#app',data: {
name: ""
},methods: {
onButtonClick() {
axios
.post("http://localhost:5000/greet/hello",{
Name: this.name
},{
headers: {
Authorization: "HEY"
}
})
.then((response) => {
if (response.status == 200) {
alert(response.data.message);
}
})
.catch((error) => {
console.log(error);
alert(error.response.data.message);
});
},}
})
解决方法
基本上,您在发送 Authorization 标头时不允许使用 Allowed-Origin: *
,因此您必须指定允许的域,您可以通过更改 CORS 中间件而不是使用默认的 {{1 }}
你可以使用这样的东西
router.Use(cors.Default())
您还可以将 router.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:5500"},AllowMethods: []string{"GET","POST","PUT","PATCH","DELETE","HEAD"},AllowHeaders: []string{"Origin","Content-Length","Content-Type","Authorization"},ExposeHeaders: []string{"Content-Length"},AllowCredentials: true,MaxAge: 12 * time.Hour,}))
cors.Config 属性用于动态逻辑(如果您想支持多个域)。
请注意 AllowOriginFunc
属性如何包含您的 vue 项目的域。显然您可以允许更多的标题,但这里列出的是您之前使用默认配置允许的标题
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。