Angular 和 Golang“不存在訪問控制允許來源......”
我正在使用 Angular 構建前端 GUI 應用程序,以與用 Go 編寫的 API 服務器進行交互。我嘗試在客戶端和服務器兩端添加標頭,但沒有成功。我嘗試禁用 http 攔截器,因此它不會添加 JWT 令牌,在這種情況下我會收到未經授權的訪問錯誤,這是預期的。但是,無論我將令牌添加到請求中(無論是使用攔截器還是在發出獲取請求之前手動),未經授權的訪問錯誤都會消失(到目前為止一切順利),但隨后會出現丟失標頭錯誤。服務器應該返回存儲文章的 JSON 數據,它可以與 Postman 和我的其他普通 JS 前端配合使用。去代碼: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)))角度獲取請求:this.http.get('http://localhost:8000/api/articles').subscribe(res => { console.log(res);},err => console.log(err));角度 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); } }}我收到此錯誤:...請求..已被 CORS 策略阻止:對預檢請求的響應未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”標頭。
查看完整描述