Go(Gin)和React一起调用API
撰写文章的原因
由于在使用Go和React创建应用程序时遇到了API调用的问题,所以为了不忘记,我将其记录下来(Vite除外)。希望对那些不理解的人有所帮助。
准备好了
环境
-
- Mac OS
-
- VSCode
-
- Go v1.19
- React v18.2.0
安装等
//プロジェクトフォルダ作成(今回はsample)
$ mkdir sample
$ cd sample
//backendフォルダ作成
$ mkdir backend
$ cd backend
// main.goファイル作成
$ touch main.go
// go.modファイル作成
$ go mod init sample
// Ginインストール
$ go get -u github.com/gin-gonic/gin
//
$ cd ..
// Reactプロジェクト作成(Viteも可)
$ npx create-react-app frontend
//axiosインストール
cd frontend
npm install axios
// VSCode開く
$ code .
目录结构
sample
├── backend
│ └── Go系
└── frontend
└── React系
代码 (daima)
这次我们不在Go端进行CORS设置
参考网站
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
type JsonRequest struct {
Message string `json:"message"`
}
func main() {
router := gin.Default()
// Go -> React
router.GET("/api", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"message": "This message from Go api",
})
})
// React -> Go
router.POST("/api/message", func(ctx *gin.Context) {
var jr JsonRequest
if err := ctx.ShouldBindJSON(&jr); err != nil {
fmt.Println("Error Occured")
} else {
fmt.Println(jr.Message)
}
})
// http://localhost:8080
router.Run()
}
请参考以下网站
import './App.css';
import {useEffect, useState} from'react';
import axios from 'axios';
function App() {
const [data, setData] = useState();
// Go -> React
useEffect(() => {
const getData = async () => {
try{
const res = await axios.get('/api');
setData(res.data);
}catch(e){
console.log(e);
}
}
getData();
}, [])
// React -> Go
const createPost = () => {
axios.post('/api/message', {message: 'This message from React'});
}
return (
<div className="App">
<h1>Hello, World</h1>
<div>Recieved -> {data ? data.message : 'No data'}</div>
<br/><br/>
<button onClick={createPost}>Create POST</button>
</div>
);
}
export default App;

当执行时,AxiosError会出现,因为React的端口是3000,而Go的端口是8080,因此无法找到请求。

为了回避(通过Go端口进行通信),请在frontend文件夹下的package.json文件中添加”proxy”: “http://localhost:8080″,(本次是为了开发者设置)。
参考网站:
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:8080",
}
对于Vite而言,在vite.config.js文件中添加以下内容。
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server:{
proxy: {
"/api": {
target: "http://localhost:8080",
changeOrigin: true,
}
}
}
})

当点击Create POST按钮时,可以确认我们可以接收到React发出的值。
