“This is the 14th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

preface

The backend framework can automatically switch database connections based on environment variables. The front-end framework can also read the relevant environment variables to switch the adaptive backend interface domain name. Today I added a lot of simulation data to the database and then configured the cross-domain Settings to see the effect of the real line.

What is cross-domain

Now the front – end separation of the project is very popular, here is a little in my own words to summarize what is cross-domain. In the era when the front and back end were not separated, the front and back end codes were on the same server. At that time, there was no front-end scaffolding, and the front-end code was in the backend framework. So the front-end requests are all requests to their own framework interface, generally speaking, that is, the source URL of the front-end static file and the source URL of the interface request are the same, they are from the same domain name, at that time, there will be no cross-domain problems, but now now, there will be cross-domain problems when the front and back end are separated. The front-end javascript needs to request interfaces or resources from different domains. Especially in today’s microservices architecture, a back-end system is often broken down into many parts, and each part resolves into many domain names, which can be used by many front-end projects. This can lead to a very insecure web page. Some requests for resources change suddenly, the web page will display chaos, or the resources of your server will be used by others, so the browser will default not to allow this to happen in order to avoid inexplicable problems. The back end must also tell the browser to Allow cross-domain Access (” access-Control-allow-origin “, “*”) via the header of the response when responding to the front-end call.

Create an environment variable file

Create two new files named.env and.env.master in the project root directory.

ENV = 'production'

VUE_APP_BASE_API = 'http://localhost:8080'

Copy the code
ENV = 'master'
VUE_APP_BASE_API = 'http://www.*****.com'

Copy the code

After a while, it turns out that the vue. Config. js proxy Settings are used by the backend interface in the local environment, but are not used online. So now I need to change the contents of main.js:

import Vue from 'vue' import App from './App.vue' import axios from 'axios' Vue.config.productionTip = false Prototype.$axios = axios if (process.env. Env == 'production') {axios.defaults.baseURL = '/ API '} else { Axios. Defaults. BaseURL = process. The env. VUE_APP_BASE_API / / key code} axios. Defaults. Headers. Post = [' the content-type '] 'application/json'; new Vue({ render: h => h(App), }).$mount('#app')Copy the code

Read the ENV’s environment variable to replace axios.defaults.baseURL, but it’s not enough to just do that, you need to do the backend Settings

Back-end cross-domain Settings

The back end is relatively simple, only Gin middleware needs to be added, on the premise that the interface can be accessed on the public network:

Now create a new middleware directory in your project root directory and create a new middleware.go file in that directory and enter the following:

package middleware

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func Cors() gin.HandlerFunc {
	return func(context *gin.Context) {
		method := context.Request.Method
		context.Header("Access-Control-Allow-Origin", "*")
		context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		context.Header("Access-Control-Allow-Credentials", "true")
		if method == "OPTIONS" {
			context.AbortWithStatus(http.StatusNoContent)
		}
		context.Next()
	}
}

Copy the code

Then import the file in the project root directory main.go file

mainmethodsr := gin.Default()The next one loads the middleware:

r.Use(middleware.Cors())
Copy the code

Note that in the Gin framework Use means middleware

So we can put the front and back code online and see it. The front-end can directly access the data of the back-end interface:

Conclusion:

I added a lot of content until I finally found that the style was still a bit wrong. After the right side of the data became more, I compressed the content of the fixed width on the left side and adjusted it in the next article.