使用uniapp发送请求时发现跨域问题,在加了两条常用的跨域Header后使用ajax测试通过,但是uniapp依旧不行。需要加上后面两条才能正常通过预检请求。
第一个问题:Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
// 发送预检请求没有获取到正确的http状态
c.Status(http.StatusOK)
第二个问题:Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
// 允许请求标头字段授权。
c.Header("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
完整解决跨域代码
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
// 有预检需要加上这两条
c.Header("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
c.Status(http.StatusOK)