单页面应用 (SPA)
本项目演示了如何使用 React 作为前端,以及 Go 配合 Fiber 框架作为后端来搭建单页面应用 (SPA)。
先决条件
请确保已安装以下软件
- Golang
- Node.js
- npm
设置
-
克隆仓库
git clone https://github.com/gofiber/recipes.git
cd recipes/spa -
安装前端依赖
cd frontend
npm install -
安装后端依赖
cd ../backend
go get
使用方法
构建前端资源
-
构建前端资源
cd frontend
npm run build -
监听前端资源变化
npm run dev
运行应用
- 启动 Fiber 后端应用
cd backend
go run main.go
示例
以下是在 Fiber 后端设置基本路由以服务 React 前端的示例
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
)
func main() {
app := fiber.New()
// Middleware
app.Use(logger.New())
// Serve static files
app.Static("/", "./frontend/dist")
// API routes
app.Get("/api/hello", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"message": "Hello, World!"})
})
// Start server
app.Listen(":3000")
}