已被CORS政策屏蔽

已被CORS政策屏蔽

本文介绍了已被CORS政策屏蔽:对预检请求的响应未通过访问控制检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created trip server. It works fine and we are able to make POST request by Insomnia but when we make POST request by axios on our front-end, it sends an error:

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

我们在axios上的要求:

Our request on 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)
   });
}

我的go文件:

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上所说的那样,它工作得很好,但是当我们发出axios POST请求时,在浏览器的控制台上会出现以下内容:

As I said before on Insomnia it works great, but when we make an axios POST request, on browser's console following appears:

推荐答案

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

I believe this is the simplest example:

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添加标题,并且当然可以允许任何所需的标题和方法.

You can also add a header for Access-Control-Max-Age and of course you can allow any headers and methods that you wish.

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

Finally you want to respond to the initial request:

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

编辑(2019年6月):我们现在为此使用大猩猩.他们的资料得到了更积极的维护,并且他们已经做了很长时间了.保留链接到旧链接,以防万一.

Edit (June 2019): We now use gorilla for this. Their stuff is more actively maintained and they have been doing this for a really long time. Leaving the link to the old one, just in case.

下面的旧中间件建议:当然,仅为此使用中间件可能会更容易.我认为我没有使用过它,但是强烈建议这个.

Old Middleware Recommendation below:Of course it would probably be easier to just use middleware for this. I don't think I've used it, but this one seems to come highly recommended.

这篇关于已被CORS政策屏蔽:对预检请求的响应未通过访问控制检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:34