Go语言 我怎样才能发布我的API给任何人使用呢?

hzbexzde  于 2023-03-06  发布在  Go
关注(0)|答案(1)|浏览(158)

我有一个服务器在go,gin和libpq,我的前端是试图消费的API,但它给出了一个错误..此错误:

Access to fetch at 'https://--brapoio-t.azurewebsites.net/-/-o' from origin 'https://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

(the url被故意更改以询问堆栈溢出问题)
我的项目是这样划分的:
主要路线://路由
main.go:

package main

输入(“os”

"github.com/gin-gonic/gin"
"github.com/guilherm5/brapoio/routes"


函数main(){

Router := gin.New()
Router.Use(gin.LoggerWithWriter(gin.DefaultErrorWriter))

//tem toda minha parte de configuração
routes.ConfiguracaoSistema(Router)
routes.ConfiguracaoModulo(Router)
routes.ModuloSistema(Router)
routes.ArvoreMenu(Router)
routes.ModuloArvoreMenu(Router)

//tem toda minha parte de Usuario
routes.Usuario(Router)
routes.EmpresaUsuario(Router)
routes.CampoTabelaUsuario(Router)
routes.ProgramaUsuario(Router)
routes.FuncionalidadeProgramaUsuario(Router)
routes.TabelaUsuario(Router)
routes.ParametroFiltroTabelaUsuario(Router)
//meu servidor de autenticação
routes.JWTAutentication(Router)

listenAddr := ":1000"

if val, ok := os.LookupEnv("FUNCTIONS_CUSTOMHANDLER_PORT"); ok {
    listenAddr = ":" + val
}

Router.Run(listenAddr)

}
包裹路线示例:

package routes

import (
    "github.com/gin-gonic/gin"
    "github.com/guilherm5/brapoio/controllers"
)

//NAO ESQUECER DE FAZER AZURE

func ModuloSistema(c *gin.Engine) {
    c.GET("/api/moduloSistema", controllers.GetModuloSistema())
    c.GET("/api/moduloSistemaID", controllers.GetModuloSistemaID())
    c.POST("/api/moduloSistema", controllers.NewModuloSistema())
    c.PUT("/api/moduloSistema", controllers.UpdateModuloSistemao())
    c.DELETE("/api/moduloSistema", controllers.DeleteModuloSistema())
}

如何解决我的前端一直遇到的这个错误?

jmo0nnb3

jmo0nnb31#

我认为首先你应该阅读CORS来理解为什么它阻止你的前端站点访问资源。你可以阅读this doc from Mozilla来获得更多细节。对于你的Gin案例,你可以添加CORS middleware来启用它。

相关问题