rest - 已被 CORS 策略阻止 : Response to preflight request doesn’t pass access control check

标签 rest google-chrome go axios cors

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

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

我的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 请求时,在浏览器的控制台上会出现以下内容:

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

最佳答案

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

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, Authorization, X-Requested-With")

您还可以为 Access-Control-Max-Age 添加 header ,当然您可以允许任何您想要的 header 和方法。

最后你要响应最初的请求:

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

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

下面的旧中间件推荐: 当然,为此使用中间件可能会更容易。我不认为我用过它,但是this one似乎强烈推荐。

关于rest - 已被 CORS 策略阻止 : Response to preflight request doesn’t pass access control check,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57663157/

相关文章:

ios - 如何在 swift 中使用 header 完成 api 调用

rest - 按 ContentTypeId 的 SharePoint 2013 REST 查询

css - 如何摆脱 chrome 浏览器中 textarea 底部与其包装 div 之间的差距?

go - 如何使用 Go 在 Elasticsearch 查询中放置格式说明符?

rest - 嵌套资源上的 GraphQL 突变

css - 如何删除网页末尾的空白 - 仅出现在 Chrome 中

css - 如何强制 Chrome 使用 `box-sizing: content-box` ? (2 个嵌套 DIV,外部显示为 `table-cell` 。)

go - 高效附加到可变长度的字符串容器 (Golang)

templates - Golang 模板引擎管道

c# - 在 C# 中使用带有 SSL 证书的 Rest 服务