0

I am trying to post from my angular frontend to my Go API and no matter what I do it keeps posting nil to the Go API. When I test if the variables are making it to the Angular subscriber it shows that they are but for some reason it will not post to this simple Go endpoint

Here is my code any help would be very greatly appreciated:

GO API

package main

import (
    "encoding/json"
    "fmt"
    "github.com/dgrijalva/jwt-go"
    "log"
    "net/http"
    "time"
)

func main() {

    http.HandleFunc("/signin", indexHandler)
    http.HandleFunc("/welcome", Welcome)
    http.HandleFunc("/refresh", Refresh)

    // start the server on port 8000
    log.Fatal(http.ListenAndServe(":8001", nil))
}

func setupResponse(w *http.ResponseWriter, req *http.Request) {
    (*w).Header().Set("Access-Control-Allow-Origin", "*")
    (*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    (*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}

func indexHandler(w http.ResponseWriter, req *http.Request) {
    setupResponse(&w, req)
    if (*req).Method == "POST" {
        return
    }
    fmt.Println(req.Header)

    fmt.Println(req.ParseForm())
    fmt.Println(json.NewDecoder(req.Body))

}

Angular Subscriber

 login(username: string, password: string) {

    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json charset=utf-8'
        , 'Access-Control-Allow-Origin': '*'
        , 'Access-Control-Allow-Headers': 'access-control-allow-origin, access-control-allow-headers'})
    };
   return this.http.post(`${environment.APIEndpoint}/signin`, {username, password}, httpOptions).pipe(map(user => {
        // login successful if there's a jwt token in the response
        if (user && user) {
          // store user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(user));
        }

        return user;
      }));
  }

This is my Output in Go

map[User-Agent:[Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Mobile Safari/537.36] Access-Control-Request-Headers:[access-control-allow-headers,access-control-allow-origin,content-type] Referer:[http://localhost:4200/login?returnUrl=%2Fdashboard] Accept-Language:[en-US,en;q=0.9] Connection:[keep-alive] Accept:[/] Accept-Encoding:[gzip, deflate, br] Access-Control-Request-Method:[POST] Origin:[http://localhost:4200]] &{{} [] {[] 0 { false [] false 0 0} { false [] false 0 0} { } false false} 0 0 { false [] false 0 0} 0 []}

And I am then getting a CORS error in Angular which is:

Access to XMLHttpRequest at 'http://localhost:8001/signin' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

I would be very grateful if anyone can help me. I am new to both Go and Angular and am still learning how to get them to interact with each other.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Joe Alvini
  • 306
  • 1
  • 3
  • 15
  • Please check the preflight section. possible duplicate of https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe – jcuypers Mar 13 '19 at 06:30
  • remove `'Access-Control-Allow-Origin': '*' , 'Access-Control-Allow-Headers': 'access-control-allow-origin, access-control-allow-headers'` from the client, they should only be used on server. – jcuypers Mar 13 '19 at 06:36
  • @jcuypers Ok so I have taken that out and only left application/json as the content type but now while I do not get a cors error and I do see that the payload is getting sent in the browsers network tab it still shows that the data is nil when trying to request it in Go. What do I have to do to get the data in go? – Joe Alvini Mar 13 '19 at 14:36
  • sorry i'm not a `Go` guy. but isn't this: `if (*req).Method == "POST" { return }` weird? you use post to send the data and then you just exit the function with nothing (while after that you still try to print)? Try to put the print statements inside of the if statement – jcuypers Mar 13 '19 at 14:41

1 Answers1

0

make changes like so:

func indexHandler(w http.ResponseWriter, req *http.Request) {
    setupResponse(&w, req)
    if (*req).Method == "POST" {
          fmt.Println(req.Header)

          fmt.Println(req.ParseForm())
          fmt.Println(json.NewDecoder(req.Body))
    }
}

Angular client side

login(username: string, password: string) {

    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json charset=utf-8'})
    };
   return this.http.post(`${environment.APIEndpoint}/signin`, `{"username":username, "password":password}`, httpOptions).pipe(map(user => {
        // login successful if there's a jwt token in the response
        if (user && user) {
          // store user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(user));
        }

        return user;
      }));
  }
jcuypers
  • 1,774
  • 2
  • 14
  • 23
  • I get the following response when I change it map[Content-Length:[35] Origin:[http://localhost:4200] Referer:[http://localhost:4200/login?returnUrl=%2Fdashboard] Accept-Encoding:[gzip, deflate, br] Connection:[keep-alive] Accept:[application/json, text/plain, */*] User-Agent:[Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.3 Safari/537.36] Content-Type:[application/json] &{0xc420066040 [] {[] 0 { false [] false 0 0} { false [] false 0 0} { } false false} 0 0 { false [] false 0 0} 0 []} – Joe Alvini Mar 13 '19 at 18:10
  • But it seems to be posting because on the frontend it shows Payload: {username: "Joe", password: "Joe"} password: "Joe" username: "Joe" – Joe Alvini Mar 13 '19 at 18:12
  • 1
    what you call valid json is just an object according to me: valid json should look like this : `{ "username": "Joe", "password": "Joe" }`. make sure your post request has JSON.stringify(data) – jcuypers Mar 13 '19 at 18:22