【发布时间】:2018-11-21 15:44:18
【问题描述】:
创建的后端 API 使用 gin 和 go 语言
type Post struct {
ID uint `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
func main() {
// ...
r := gin.Default()
r.GET("/posts", GetPosts)
r.GET("/posts/:id", GetPost)
r.POST("/posts", CreatePost)
r.PUT("/posts/:id", UpdatePost)
r.DELETE("/posts/:id", DeletePost)
r.Run(":8080")
}
func GetPosts(c *gin.Context) {
var posts []Post
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
if err := db.Find(&posts).Error; err != nil {
c.AbortWithStatus(404)
fmt.Println(err)
} else {
c.JSON(200, post)
}
}
// ...
创建的前端使用 react 和 react-admin
src/App.js
import React from 'react';
import { Admin, Resource } from 'react-admin';
import jsonServerProvider from 'ra-data-json-server';
import { PostList } from './posts';
const dataProvider = jsonServerProvider('http://localhost:8080');
const App = () => (
<Admin dataProvider={dataProvider}>
<Resource name="posts" list={PostList} />
</Admin>
);
export default App;
src/posts.js
import React from 'react';
import { List, Datagrid, TextField } from 'react-admin';
export const PostList = (props) => (
<List {...props}>
<Datagrid>
<TextField source="id" />
<TextField source="title" />
<TextField source="body" />
</Datagrid>
</List>
);
当从 chrome 浏览器访问 http://localhost:3000 时,收到 Failed to fetch 消息。从我看到的控制台:
Failed to load http://localhost:8080/posts?_end=10&_order=DESC&_sort=id&_start=0: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我尝试在 go API 程序中添加Access-Control-Allow-Origin,但结果相同。从gin 输出我得到:
[GIN] 2018/06/12 - 18:14:50 | 404 | 1.813µs | 127.0.0.1 | OPTIONS /posts?_end=10&_order=DESC&_sort=id&_start=0
添加
添加 cors 包然后将源更改为:
package main
import (
"fmt"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
// ...
)
// ...
func main() {
r := gin.Default()
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:8080"},
}))
r.GET("/posts", GetPosts)
r.GET("/posts/:id", GetPost)
r.POST("/posts", CreatePost)
r.PUT("/posts/:id", UpdatePost)
r.DELETE("/posts/:id", DeletePost)
r.Run()
}
又遇到同样的错误:
Failed to load http://localhost:8080/posts?_end=10&_order=DESC&_sort=id&_start=0: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
这一次,gin 的输出是:
[GIN] 2018/06/13 - 11:01:59 | 403 | 7.873µs | ::1 | OPTIONS /posts?_end=10&_order=DESC&_sort=id&_start=0
【问题讨论】:
-
尝试为golang代码添加gin的
CORS中间件,允许跨域请求访问 -
@Himanshu 我添加了一个中间件但得到了相同的结果。
标签: reactjs api go cors go-gin