回答

收藏

已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查

技术问答 技术问答 120 人阅读 | 0 人回复 | 2023-09-12

我已经创建了旅行服务器。它工作正常,我们可以POST通过 Insomnia但是当我们发出请求时,POST通过过前端axios当发出请求时,它会发送一个错误:
$ O8 c' y* @2 }+ z" H
    has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.
    5 y/ E. k: Y" W# l- ^! F2 i: F
我们对 axios 的要求:
3 ]' q$ x3 Y+ _& r) \- s9 J* t
    let config = {headers: {  "Content-Type": "application/json", 'Access-Control-Allow-Origin': '*', }}let data = {  "id": 4 } axios.post('http://196.121.147.69:9777/twirp/route.FRoute/GetLists',data,config)   .then((res) => {       console.log(res)   .catch((err) => {       console.log(err)   });} # L7 j) H2 w. S  t' o- W" M
我的去文件:# |4 I* T- z. ~3 d  X* }4 z
    func setupResponse(w *http.ResponseWriter,req *http.Request)    (*w).Header().Set("Access-Control-Allow-Origin","*")    (*w).Header().Set("Access-Control-Allow-Methods",&quotOST,GET,OPTIONS,PUT,DELETE")    (*w).Header().Set("Access-Control-Allow-Headers","Accept,Content-Type,Content-Length,Accept-Encoding,X-CSRF-Token,Authorization")}func WithUserAgent(base http.Handler) http.Handler    return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request)    ctx := r.Context()    ua := r.Header.Get("Jwt")    ctx = context.WithValue(ctx,"jwt",ua)    r = r.WithContext(ctx)    setupResponse(&w,r)     base.ServeHTTP(w,r)  })}const  host     = "localhost"    port     = 5432    user     = "postgres"    password = "postgres"    dbname   = "postgres")func main()    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "            "password=%s dbname=%s sslmode=disable",                                                        host,port,user,password,dbname)    server := &s.Server{psqlInfo}    twirpHandler := p.NewFinanceServiceServer(server,nil)    wrap := WithUserAgent(twirpHandler)      log.Fatalln(http.ListenAndServe(":9707",wrap))}- v' l; g$ x  X8 {9 H
就像我以前在 一样Insomnia 上面说的,它工作得很好,但当我们发出 axiosPOST请求时,在浏览器的控制台上会出现以下内容:. w) B* w6 j5 e$ S9 R$ E* f
已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:无 HTTP ok 状态。
: L: @7 H3 O4 ^0 Z
                                                               
: `1 k+ u1 x' d. t& R& B, q    解决方案:                                                                ; Z5 h) K/ G3 \, c" N& L
                                                                我相信这是最简单的例子:# k. e% s8 I* t
    header := w.Header()header.Add("Access-Control-Allow-Origin","*")header.Add("Access-Control-Allow-Methods","DELETE,POST,GET,OPTIONS")header.Add("Access-Control-Allow-Headers","Content-Type,Access-Control-Allow-Headers,Authorization,X-Requested-With")
    7 ~# G( [! D+ n3 G' h" k& l9 g1 @
您还可以添加标题Access-Control-Max-Age,当然,你可以允许任何你想要的标题和方法。
+ ]5 i4 t, E% k2 c7 ~1 R* S8 W最后,您应响应初始请求:
6 G6 v, G- q( p% a4 W. Y7 z7 S$ K
    if r.Method == "OPTIONS"    w.WriteHeader(http.StatusOK)    return}
    1 q; w6 N/ v- b2 A/ i1 g/ P7 m
编辑(2019年 6 月):我们现在为此使用gorilla。他们的东西得到了更积极的维护,他们已经这样做了很长时间。把链接留给旧的,以防万一。
6 }! j+ m: [# W) z3 A以下旧中间件建议:    当然,使用中间件可能更容易。我不认为我用过,但这次似乎强烈推荐。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则