在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/GO/ 用 gin 開發(fā) API 如何解決 cors 問題?

用 gin 開發(fā) API 如何解決 cors 問題?

用 Go 框架 gin 開發(fā)后端 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"
回答
編輯回答
生性
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,
}))

這樣就行了

2017年8月18日 14:31