阻止了跨域请求,缺失了 Access-Control-Allow-Origin 标头
时间:2024-03-04
浏览:152
作者:佚名
欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《阻止了跨域请求,缺失了 Access-Control-Allow-Origin 标头》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!
我正在编写一个博客应用程序,其前端为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})
})
}文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《阻止了跨域请求,缺失了 Access-Control-Allow-Origin 标头》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
