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”标头。
查看完整描述