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

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

问题描述:

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.

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