1. Basic Setting

We are developing a web applications. Gin is for backend and vue is for frontend.

However, I often encouter router problems when sending request from frontend to the backend.

Here are quick rules to avoid these problems.

2. Router

//routers.go
func Router() *gin.Engine {
	r := gin.Default()
	r.Use(middleware.Cors())
	user := r.Group("/user")
	{
        user.GET("/test/", controllers.Test)
		user.GET("/", controllers.GetUsers)
		user.GET("/:id", controllers.GetUser)
        user.POST("/new", controllers.NewUser)
        user.POST("/update/:id", controllers.UpdateUser)
	}
	return r
}
<script>
// add end slash
const res = await $fetch("http://localhost:8080/user/test/")
const res = await $fetch("http://localhost:8080/user/");

// no end slash
const res = await $fetch("http://localhost:8080/user/1");
const res = await $fetch("http://localhost:8080/user/new", {
    ...
});
const res = await $fetch("http://localhost:8080/user/update/1", {
    ...
});
</script>

3. Request Body

Always use “.value” to access const data. Note that changing “const” is not allowed. Instead, changing value is ok.

<script>
const user_name = ref('');
const res = await $fetch("http://localhost:8080/user/new", {
    method: 'POST',
    body: {
        "user_name": user_name.value // add .value
    }
});
</script>

Always check data type inside the request body.

<script>
const user_name = ref('');
const user_age = ref(''); // string

const res = await $fetch("http://localhost:8080/user/update/1", {
   method: 'POST',
   body: {
       "user_name": user_name.value
       "user_age": parseInt(user_age.value, 10) // to integer
   }
});
</script>