go - CORS on golang server & javascript fetch frontend -


i have golang http server code like:

    http.handlefunc("/login", func(w http.responsewriter, r *http.request) {     log.println("new incoming request")      // authenticate     if u, p, ok := r.basicauth(); ok {       log.println("success")       return     }     log.println("failed") 

i call http endpoint js frontend, 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 following logs.

on server side:

new incoming request failed 

on browser, in developer tools logs:

fetch api cannot load http://localhost:8080/login. response preflight request doesn't pass access control check: no 'access-control-allow-origin' header present on requested resource. origin 'http://localhost:3000' therefore not allowed access. response had http status code 401. if opaque response serves needs, set request's mode 'no-cors' fetch resource cors disabled. 

can fix authentication problem ? not sure if missing related cors on server side or doing bad authentication on client side. ? thanks.

the access-control-allow-origin: * has sent server, not client. assuming in standard net/http handler function, try 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") // can add more headers here if needed     } else {         // code goes here     } } 

Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -