doudang8824 2019-06-07 16:48
浏览 72
已采纳

Angular&Golang“不存在允许访问的控制…”

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"
)
  • 写回答

2条回答 默认 最新

  • dou44364983 2019-06-07 17:20
    关注

    This issue is known as CORS. Cross Origin Resource Sharing. This is arises when the origin of the request and response is different. For example: If your project is on https://139.43.33.122:1111/ and your server is hosted on https://123.0.3.444:3000, then the origin of your request and response are completely different and thus, browser will block the response. This is the browser thing. Postman doesn't care about their origin. To receive response, there are 2 ways (maybe more but i use these 2 only).

    1. Additional Headers: If yoou have access/permission to server code, then add an additional header to the server responses: Access-Control-Allow-Origin: http://siteA.com, Access-Control-Allow-Methods: GET, POST, PUT, Access-Control-Allow-Headers: Content-Type.

    2. Use Extensions: There are multiple extensions that can bypass this restriction. IF you do not have access or permission to change the server response, then this is the way to go.I'm personally using this method only.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 preLaunchTask"C/C++: aarch64- apple-darwin22-g++-14 生成活动 文件”已终止,退出代码为-1。
  • ¥18 关于#贝叶斯概率#的问题:这篇文章中利用em算法求出了对数似然值作为概率表参数,然后进行概率表计算,这个概率表是怎样计算的呀
  • ¥20 C#上传XML格式数据
  • ¥15 elementui上传结合oss接口断点续传,现在只差停止上传和继续上传,各大精英看下
  • ¥100 单片机hardfaulr
  • ¥20 手机截图相片分辨率降低一半
  • ¥50 求一段sql语句,遇到小难题了,可以50米解决
  • ¥15 速求,对多种商品的购买力优化问题(用遗传算法、枚举法、粒子群算法、模拟退火算法等方法求解)
  • ¥100 速求!商品购买力最优化问题(用遗传算法求解,给出python代码)
  • ¥15 虚拟机检测,可以是封装好的DLL,可付费