用 Go 框架 gin 开发后端 API,本地端口为:
http://localhost:8080
基本代码为:
import (
"github.com/gin-gonic/gin"
"github.com/rs/cors"
// ...
)
type Post struct {
ID uint `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
func main() {
r := gin.Default()
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"PUT", "PATCH", "GET", "POST", "DELETE"},
AllowHeaders: []string{"content-type"},
ExposeHeaders: []string{"X-Total-Count"},
}))
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()
}
前端使用 react-admin
访问那个 API,本地端口为:
http://localhost:3000
基本代码为:
package main
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;
在 Chrome 浏览器中访问 http://localhost:3000/#/posts
时,从浏览器控制台看到如下信息:
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.
index.js:2178 Warning: Missing translation for key: "Failed to fetch"
这样就行了