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.