[英]CORS header ‘Access-Control-Allow-Origin’ missing - Access-Control-Allow-Origin already given
[英]Cross-Origin Request Blocked, header Access-Control-Allow-Origin missing
我正在寫一個博客應用程序,該應用程序的前端為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 });
});
我搜索並嘗試了數小時來解決此問題,但沒有運氣。
感謝Slotheroo提出的使用nginx的建議,這是解決這個問題的唯一可能的方法。我使用nginx代理請求並將前端和后端都路由到8000端口。 我將在這里留下我的Nginx服務器配置和對代碼所做的更改的示例,以便將來對任何人都有用:)
(請注意,使用像“ localhost”這樣的回送ip會影響加載和發送請求的性能,因此請使用計算機的確切ip來克服這種性能問題)
nginx.conf
server {
listen 8000;
server_name localhost;
location / {
proxy_pass http://localhost:3000;
}
location /getposts {
proxy_pass http://localhost:5000/getposts;
}
}
已將localhost:8000添加到后端的允許源中
AllowedOrigins: []string{"http://localhost:8000"},
現在將請求發送到8000端口
fetch('http://localhost:8000/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})
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.