one-api icon indicating copy to clipboard operation
one-api copied to clipboard

必须要自己改一下main.go里才能支持跨域

Open chendind opened this issue 1 year ago • 1 comments

例行检查

  • [x] 我已确认目前没有类似 issue
  • [x] 我已确认我已升级到最新版本
  • [x] 我已完整查看过项目 README,尤其是常见问题部分
  • [x] 我理解并愿意跟进此 issue,协助测试和提供反馈
  • [x] 我理解并认可上述内容,并理解项目维护者精力有限,不遵循规则的 issue 可能会被无视或直接关闭

问题描述 发现localhost:3000和https://a.nextweb.fun/ 调用接口 都会报跨域错误 CORS error

修改方案

import (
	"embed"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"one-api/common"
	"one-api/controller"
	"one-api/middleware"
	"one-api/model"
	"one-api/router"
	"os"
	"strconv"
	"net/http"
)
// 允许的域名列表
var allowedOrigins = map[string]bool{
	"http://localhost:3000": true,
	"https://a.nextweb.fun": true,
}
// CORS 中间件
func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		origin := c.GetHeader("Origin")

		// 检查请求的 Origin 是否在允许列表中
		if _, exists := allowedOrigins[origin]; exists {
			// 设置允许的 Origin
			c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
		}

		// 其他 CORS 相关的设置
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		c.Next()
	}
}
func main() {
// 省略
	server.Use(CORSMiddleware()) // 添加 CORS 中间件
//省略
}

chendind avatar Nov 26 '23 15:11 chendind

也是遇到一样的问题,有没有更好的允许全局跨域的办法。 [ChatApi v0.5.10-alpha.1]

suwubee avatar Dec 12 '23 11:12 suwubee

这个可以

14790897 avatar Jun 02 '24 14:06 14790897

成功跨域

14790897 avatar Jun 04 '24 00:06 14790897

但是请求子路径不行

14790897 avatar Jun 05 '24 09:06 14790897

用nginx可以全局跨域,在main.go修改还是不能做到全局跨域

14790897 avatar Jun 09 '24 11:06 14790897