0
votes

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.

1
Please check the preflight section. possible duplicate of stackoverflow.com/questions/43871637/… - jcuypers
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
@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
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

1 Answers

0
votes

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