I am using Angular to build a front-end GUI app to interact with my API server written in Go.
I've tried adding the header on both ends, client and the server, yet no luck. I've tried disabling the http interceptor, so it doesn't add the JWT token in which case I get the unauthorized access error, which is expected. But wherever I add the token to the request (either with the interceptor or manually before making the get request) the unauthorized access error is gone (so far so good), but then the missing header error appears. The server should return JSON data of stored articles, and it works with Postman and my other vanilla JS front-end.
Go code:
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./index.html")
})
allowedHeaders := handlers.AllowedHeaders([]string{"X-Requested-With"})
allowedOrigins := handlers.AllowedOrigins([]string{"*"})
allowedMethods := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"})
r.HandleFunc("/login", GetTokenHandler).Methods("POST")
apiRouter := r.PathPrefix("/api").Subrouter()
apiRouter.Use(jwtMiddleware.Handler)
apiRouter.HandleFunc("/articles", getArticles).Methods("GET")
apiRouter.HandleFunc("/articles/{id}", getArticle).Methods("GET")
apiRouter.HandleFunc("/articles", createArticle).Methods("POST")
apiRouter.HandleFunc("/articles/{id}", updateArticle).Methods("PUT")
apiRouter.HandleFunc("/articles/{id}", deleteArticle).Methods("DELETE")
fmt.Println("Server running on port", port)
log.Fatal(http.ListenAndServe(port, handlers.CORS(allowedHeaders, allowedOrigins, allowedMethods)(r)))
Angular get request:
this.http.get('http://localhost:8000/api/articles')
.subscribe(res => {
console.log(res);
},
err => console.log(err));
Angular HttpInterceptor:
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem("token");
if (token) {
const cloned = req.clone({
headers: req.headers.append("Authorization", "Bearer " + token)
});
return next.handle(cloned);
}
else {
return next.handle(req);
}
}
}
I am getting this error:
... request.. has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Edit: Go imports:
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"time"
jwtmiddleware "github.com/auth0/go-jwt-middleware"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)