“This is the 21st day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

preface

The last chapter talked about the basic knowledge of the framework, today I want to access the back-end framework interface, and then found a series of problems, found that you need to log in to enter the framework list, there are cross-domain errors, first need to set the environment variable, remove the simulation data

The front to modify

Setting environment Variables

Change the.env.development file name to.env, since the Gin framework port is 8080, and then change it to:

# just a flag
ENV = 'development'

# base api
VUE_APP_BASE_API = 'http://localhost:8080'

Copy the code

Env. production file, which is not used today for CI implementation.

# just a flag
ENV = 'production'

# base api
VUE_APP_BASE_API = 'http://api.tuwei.space'

Copy the code

Modifying a local proxy:

Add the following content to the vue. Config. j file devServer configuration (the address of your local Gin framework is http://localhost:8080) :

    proxy: {
      [process.env.VUE_APP_BASE_API]: {
        target: 'http://localhost:8080',
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
        }
      }
    },
Copy the code

See the screenshot for the specific location:

After modifying this network request does not go through the analog data directly request the back-end interface

Change the API request path for login

Change SRC/API /user.js to change the USL address of all routing methods slightly. For example, the URL of the login method is now:

url: '/vue-admin-template/user/login',
Copy the code

To:

url: '/admin/user/login',
Copy the code

The same goes for the other two. Take a look at the complete document:

import request from '@/utils/request'

export function login(data) {
  return request({
    url: '/admin/user/login',
    method: 'post',
    data
  })
}

export function getInfo(token) {
  return request({
    url: '/admin/user/info',
    method: 'get',
    params: { token }
  })
}

export function logout() {
  return request({
    url: '/admin/user/logout',
    method: 'post'
  })
}

Copy the code

Change the default status code

So now we need to change the code, the default status code 20000 is successful, my own Gin framework’s success status code is 200 change SRC /utils/request.js around line 49

if (res.code ! = = 20000) {Copy the code

Modified to

if (res.code ! = = 200) {Copy the code

The back-end to modify

From the beginning of the route to the last service, the purpose is to directly simulate the login, do not do the detailed account password authentication, this is a bit complicated and will be reserved for later

Add the routing

Add contents to the router/router.go file:

	adminuser := router.Group("/admin/user")
	{
		adminuser.POST("/login", controller.Login)
		adminuser.GET("/info", controller.Info)
	}
Copy the code

Adding a Controller

Route to the controller, pretend to accept the parameters of the front end and add something to the controller/controller.go file:

func Login(c *gin.Context) { var json request.LoginRequest if err := c.ShouldBindJSON(&json); err ! = nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } result := global.NewResult(c) data, err := service.Login(json) if err ! = nil { result.Error(5201, err.Error(), Return} result.success (data)} func Info(c *gin.Context) {result := global.newresult (c) result.success (" Info ") }Copy the code

Adding a validator

Add content to the request/request.go file, pretending to validate arguments from the front end:

type LoginRequest struct {
	Username string `form:"username" json:"username" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
}
Copy the code

Adding a service method

Add content to the service/service.go file:

func Login(json request.LoginRequest) (id string, err error) {

	return "tokentokentokentokentokentokentoken", nil
}
Copy the code

Resolving cross domain & summary

Rerun both frameworks, absolutely, because the front-end framework must rerun the local agent set up for this to take effectNow that I have entered the background, I find that the console error:

And cross-domain error? I thought it was set up in the beginning. Then it was found that there was an X-token in the header and the backend did not add it. It is ok to modify the middleware in Gin or the default token name of VUe-admin-template. I am familiar with Gin and modify the Gin middleware

Modify themiddleware/middleware.go

context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")

Copy the code

To:

context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,x-token")
Copy the code

Restart the front end, especially pay attention to the front end, set the local proxy must restart to take effect, now found that the console did not report an error, perfect solution to the cross-domain problem, the next chapter will talk about how to access the back-end interface.