登录
首页 >  Golang >  Go问答

阻止了跨域请求,缺失了 Access-Control-Allow-Origin 标头

来源:stackoverflow

时间:2024-03-04 09:24:25 151浏览 收藏

欢迎各位小伙伴来到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学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>