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 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)