admin管理员组

文章数量:1410674

I have a golang HTTP server with code like:

    http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
    log.Println("New ining request")

    // Authenticate
    if u, p, ok := r.BasicAuth(); ok {
      log.Println("Success")
      return
    }
    log.Println("Failed")

I call this HTTP endpoint from a JS frontend, a react app deployed on port 3000, using code:

      fetch('http://localhost:8080/login', {
            method: 'post',
            headers: {
                'Authorization': 'Basic ' + btoa(authHeader),
                'Content-Type': 'application/x-www-form-urlencoded',
                'Access-Control-Allow-Origin': '*'
            },
                body: 'A=1&B=2'
            })
            .then(function (response) {
                console.log("Authentication Success")
            })
            .catch(function (err) {
                console.log("Authentication fail", err)
            });

The above code fails with the following logs.

On the server side:

New ining request
Failed

On the browser, in the developer tools logs:

Fetch API cannot load http://localhost:8080/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Can someone help fix the authentication problem ? I am not sure if I am missing something related to CORS on the server side or doing bad authentication on the client side. Any help ? Thanks.

I have a golang HTTP server with code like:

    http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
    log.Println("New ining request")

    // Authenticate
    if u, p, ok := r.BasicAuth(); ok {
      log.Println("Success")
      return
    }
    log.Println("Failed")

I call this HTTP endpoint from a JS frontend, a react app deployed on port 3000, using code:

      fetch('http://localhost:8080/login', {
            method: 'post',
            headers: {
                'Authorization': 'Basic ' + btoa(authHeader),
                'Content-Type': 'application/x-www-form-urlencoded',
                'Access-Control-Allow-Origin': '*'
            },
                body: 'A=1&B=2'
            })
            .then(function (response) {
                console.log("Authentication Success")
            })
            .catch(function (err) {
                console.log("Authentication fail", err)
            });

The above code fails with the following logs.

On the server side:

New ining request
Failed

On the browser, in the developer tools logs:

Fetch API cannot load http://localhost:8080/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Can someone help fix the authentication problem ? I am not sure if I am missing something related to CORS on the server side or doing bad authentication on the client side. Any help ? Thanks.

Share Improve this question asked Nov 8, 2016 at 11:04 SankarSankar 6,55112 gold badges68 silver badges97 bronze badges 3
  • show the go setup for the cors please. – user4466350 Commented Nov 8, 2016 at 11:12
  • Access-Control-Allow-Origin is not a request header it should be on the server response. read en.wikipedia/wiki/… – Nima Ghotbi Commented Nov 8, 2016 at 11:25
  • Fetch API cannot load http://localhost:8080/login. Response for preflight has invalid HTTP status code 401 is the error message that I get if I add w.Header().Set("Access-Control-Allow-Origin", "*") in the server HTTP handler. As of now the server code does not have any CORS related code and I am looking for that exactly. – Sankar Commented Nov 8, 2016 at 12:16
Add a ment  | 

2 Answers 2

Reset to default 4

The Access-Control-Allow-Origin: * has to be sent from the server, not by the client. Assuming you are in a standard net/http handler function, try this code:

func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    if (r.Method == "OPTIONS") {
        w.Header().Set("Access-Control-Allow-Headers", "Authorization") // You can add more headers here if needed
    } else {
        // Your code goes here
    }
}

First - you need to use schema in your handler:

w.Header().Set("Access-Control-Allow-Origin", "*")
    if (r.Method == "OPTIONS") {
        w.Header().Set("Access-Control-Allow-Headers", "Authorization") // You can add more headers here if needed
    } else {
        // Your code goes here
    }

But before it you need to specify in main "OPTIONS":

router.HandleFunc("/your_route/", your_method).Methods("POST", "OPTIONS")

It's because your browser doing 2 request - first to check ability to use some headers (Authorization for example) and next step is posting data

本文标签: goCORS on golang server amp javascript fetch frontendStack Overflow