小编典典

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

go

我已经创建了旅行服务器。它工作正常,我们能够POST通过 Insomnia发出请求,但是当我们POST在前端通过 axios发出请求时,它会发送一个错误:

has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

我们对 axios 的要求:

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)
   });
} 

我的去文件:

func setupResponse(w *http.ResponseWriter, req *http.Request) {
    (*w).Header().Set("Access-Control-Allow-Origin", "*")
    (*w).Header().Set("Access-Control-Allow-Methods", "POST,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))
}

正如我之前在 Insomnia 上所说的,它工作得很好,但是当我们发出 axiosPOST请求时,在浏览器的控制台上会出现以下内容:

已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。


阅读 375

收藏
2021-12-14

共1个答案

小编典典

我相信这是最简单的例子:

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")

您还可以添加标题Access-Control-Max-Age,当然您可以允许任何您希望的标题和方法。

最后,您要响应初始请求:

if r.Method == "OPTIONS" {
    w.WriteHeader(http.StatusOK)
    return
}

编辑(2019 年 6 月):我们现在为此使用gorilla。他们的东西得到了更积极的维护,而且他们已经这样做了很长时间。把链接留给旧的,以防万一。

下面的旧中间件建议: 当然,为此使用中间件可能会更容易。我不认为我已经用它,但是这一次似乎来得强烈推荐。

2021-12-14