在前端使用react-admin
访问gin
开发的API后端。
从Chrome浏览器访问网址时:
从Chrome Console
收到此消息:
fetch.js:41 OPTIONS http://localhost:8080/posts?_end=10&_order=DESC&_sort=id&_start=0 403 (Forbidden)
但是如果从浏览器访问上面的uri,它可以返回json结果。
从gin
开发的API输出中得到以下消息:
[GIN] 2018/06/13 - 16:38:16 | 403 | 1.995µs | ::1 | OPTIONS /posts?_end=10&_order=DESC&_sort=id&_start=0
答案 0 :(得分:0)
由于前端和后端的来源不同(分别为localhost:3000和localhost:8080),因此您需要在后端设置CORS以允许localhost:3000访问它。
答案 1 :(得分:0)
在服务器端应用程序中设置访问控制允许响应的原始标题将解决问题。
添加,
CREATE OR REPLACE VIEW view_events AS
(
SELECT
"rank"() OVER (PARTITION BY "tb1"."innerid" ORDER BY "tb1"."date" ASC) "r"
, "tb2"."opcode"
, "tb1"."innerid"
, "tb1"."date"
, From_iso8601_timestamp(tb1.date) as "real_date"
, "tb2"."eventtype"
, "tb1"."fuelused"
, "tb1"."mileage"
, "tb1"."latitude"
, "tb1"."longitude"
FROM
rt_message_header tb1
, rt_messages tb2
WHERE ((("tb1"."uuid" = "tb2"."header_uuid") AND ("tb2"."opcode" = '39')) AND ("tb2"."type" = 'event'))
ORDER BY "tb1"."innerid" ASC, "tb1"."date" ASC
)
在你的服务员代码中。
答案 2 :(得分:0)
您应该添加CORS中间件
main.go:
r := gin.Default()
r.Use(CORSMiddleware())
CORSM中间件:
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(200)
} else {
c.Next()
}
}
}