0

我正在编写一个博客应用程序,它的前端是 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 });
  });

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

4

1 回答 1

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 添加到后端的 Allowed Orgins

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})
              })
    }
于 2018-07-11T14:39:19.873 回答