dst2007 2018-07-10 15:52
浏览 187
已采纳

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

I was writing a blog application which has front end in react + typescript and backend in go iris. I'm doing a get request to fetch blog content. Backend runs at localhost:5000 and node at localhost:3000.But it fails with the error

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/getposts. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I have already configured CORS in the backend

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)

This is how I send request

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 });
  });

I searched and tried for hours to fix this problem but no luck.

  • 写回答

1条回答 默认 最新

  • dousi2013 2018-07-11 14:39
    关注

    Thanks to Slotheroo for his suggestion to use nginx and that was the only possible way i could over come this problem.I used nginx to proxy the requests and route both front end and back end to 8000 port. I will leave a sample of my nginx server configuration and changes made to code here so that it helps anyone in future :)

    (Please note that using loop back ip like "localhost" can affect performance on loading and sending request therefore use exact ip of the machine to overcome such performance issue)

    nginx.conf

    server {
            listen       8000;
            server_name  localhost;
    
            location / {
                proxy_pass http://localhost:3000;
            }
            location /getposts {
                proxy_pass http://localhost:5000/getposts;
            }
    
        }
    

    Added localhost:8000 to Allowed Orgins in backend

    AllowedOrigins:   []string{"http://localhost:8000"},
    

    request is now send to 8000 port

    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})
                  })
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么在stm32门禁成品上增加记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app