跨域请求被阻止,标头访问控制允许源丢失

时间:2018-07-10 15:52:47

标签: reactjs typescript go fetch go-iris

我正在编写一个博客应用程序,该应用程序的前端为react +打字稿,后端为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 });
  });

我搜索并尝试了数小时来解决此问题,但没有运气。

1 个答案:

答案 0 :(得分:1)

感谢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})
              })
    }
相关问题