在 go 框架中使用 gorillamux 启用 cors,通过设置 http 头部允许客户端跨域请求。在前端框架(如 axios)中,处理 cors 响应以访问来自后端的数据。实战案例 演示了 go api 中 cors 配置和 react 应用程序中的响应处理。
Go 框架与前端框架跨域资源共享的实践指南
简介
跨域资源共享 (CORS) 是浏览器安全的一个重要机制,它限制了不同源的 Web 应用程序之间的 HTTP 请求。当您使用 Go 框架构建后端服务和前端框架构建 Web 应用程序时,您可能需要启用 CORS 以允许客户端与您的后端应用程序进行交互。
配置 Go 框架以启用 CORS
在 Go 框架中,可以通过 HTTP 处理程序中间件启用 CORS。以下是一个使用 [GorillaMux](https://github.com/gorilla/mux) 的示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import (
"github.com/gorilla/mux"
)
func CORS(router mux.Router) {
router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
})
}
配置前端框架以处理 CORS 响应
在前端框架中,您需要处理来自后端的 CORS 响应。以下是如何在 Axios 中配置:
1
2
3
axios.defaults.headers.common[Access-Control-Allow-Origin] = ;
axios.defaults.headers.common[Access-Control-Allow-Methods] = GET, POST, PUT, DELETE, OPTIONS;
axios.defaults.headers.common[Access-Control-Allow-Headers] = Content-Type, Authorization;
实战案例
考虑以下实战案例 :您正在构建一个 Go API 来提供用户数据,并使用 React 应用程序作为前端。
在 Go 框架中启用 CORS
在您的 Go API 路由器文件中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main
import (
"github.com/gorilla/mux"
"github.com/your-package/api/handlers"
)
func main() {
r := mux.NewRouter()
CORS(r)
r.HandleFunc("/users", handlers.GetUsers).Methods("GET")
... // 其他路由
}
在 React 应用程序中处理 CORS 响应
在您的 React 应用程序中:
1
2
3
4
5
6
7
8
9
10
import axios from axios;
const apiClient = axios.create({
baseURL: http://localhost:8080/api,
withCredentials: true,
});
apiClient.get(/users).then(res => {
console.log(res.data);
});
结论
通过正确配置 Go 框架和前端框架,您可以实现跨域资源共享并允许客户端与您的后端应用程序进行交互。以上指南提供了逐步说明和实战案例 ,以帮助您解决跨域问题。
以上就是golang框架与前端框架跨域资源共享的实践指南的详细内容,更多请关注其它相关文章!