用 gin 开发 API 如何解决 cors 问题?

新手上路,请多包涵

用 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"
阅读 11.6k
1 个回答
import (
"github.com/gin-contrib/cors"
)



gin.Use(cors.New(cors.Config{
        AllowOriginFunc:  func(origin string) bool { return true },
        AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "PATCH"},
        AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type"},
        AllowCredentials: true,
        MaxAge:           12 * time.Hour,
}))

这样就行了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题