我正在编写一个博客应用程序,它的前端是 react + typescript,后端是 go iris。我正在做一个获取博客内容的请求。后端在 localhost:5000 和节点在 localhost:3000 运行。但它失败并出现错误
跨域请求被阻止:同源策略不允许在http://localhost:5000/getposts读取远程资源。(原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。
我已经在后端配置了 CORS
Cors := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:3000"},
AllowCredentials: true,
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"},
AllowedHeaders: []string{"Cache-Control", "X-File-Name", "X-Requested-With", "X-File-Name", "Content-Type", "Authorization", "Set-Cookie", "Cookie"},
Debug: true,
})
authConfig := basicauth.Config{
Users: map[string]string{USER_NAME: PASSWORD},
Realm: "Authorization Required", // defaults to "Authorization Required"
Expires: time.Duration(30) * time.Minute,
}
authentication := basicauth.New(authConfig)
app := iris.New()
app.Use(Cors)
app.Get("/getposts", authentication, GetPostsHandler)
这就是我发送请求的方式
fetch("http://localhost:5000/getposts", {
method: "get",
credentials: "include",
mode: "cors",
headers: [
["Content-Type", "application/json"],
["Authorization", "Basic " + btoa("Sreyas:password")]
]
})
.then(response => {
if (response.ok) {
response.json().then(rawdata => {
this.setState({ blogdata: rawdata });
});
} else {
console.log("No posts");
this.setState({ blogdata: null });
}
})
.catch(error => {
console.log("Server Error");
this.setState({ blogdata: null });
});
我搜索并尝试了几个小时来解决这个问题,但没有运气。