Recently I have been working on a small project. I have worked on several systems, mainly using Extjs and SpringMVC. Vue read about it a little bit, looked at the official documentation and felt pretty good (compared to Extjs, “pretty good” doesn’t really express it…) . Because the original SpringMVC architecture was built by others, it was just a copycatted development, and I didn’t have enough energy to learn more about it. Then I decided on the project plan, Vue plus Springboot, almost zero basis while learning, although the time requirement is very tight to make myself a lot of pressure, but finally the development was completed as scheduled ~

Architecture plan

Front end: Vux to do mobile web version (friends recommend, also really slip. It’s fairly well-documented, but I still haven’t figured out how InlineCalendar’s marks work.)

Back end: Springboot refer to @mr_ early morning column, step by step build frame. Thank you!

Database: MySQL

Routing check

1. Define routes: Determine whether validation is required by setting meta. I have written all of them

const routes = [
    {  
        path: '/'.component: Login},
    {  
        path: '/home'.meta: {auth:true}, // Set the current route to require verification. Routes that do not require verification are not written
        component: Home
    },{  
        path: '/Reserve'.meta: {auth:true},   
        component: Reserve
    },{  
        path: '/Cancel'.meta: {auth:true},   
        component: Cancel
    },{  
        path: '/WorkInfo'.meta: {auth:true},  
        component: WorkInfo
    },{   
        path: '/Detail/:type/:date'.meta: {auth:true},   
        component: Detail
    }]
    const router = new VueRouter({  routes})Copy the code

2. Intercept each request through the routing hook to check whether the user has logged in.

There is a small hole here, I originally saved the user information in Vuex, and then went to verify, cheerfully swiped a new, and GG. Later I checked the data, and the data refresh in Vuex would be emptied. SessionStorage was used to store user information for verification. This is cleared when the browser is closed. (distinguish localStorage, is the basic knowledge, but I am the first time to use ~)

// Intercept router. BeforeEach ((to,from,next) => {
  if(to.matched.some( m= > m.meta.auth)){           
    var userInfo = JSON.parse(sessionStorage.getItem('userInfo'));  // Verify the route
        if(userInfo) { // Already logged in
            next()   // Go to the page you have set
        }      
        else{               Query :{Rurl: to.fullPath} indicates that the current route information is passed to facilitate the login and jump back.
            next({path:'/'.query: {Rurl: to.fullPath} })      
        }  
     } 
     else{next ()}})Copy the code

Cross-domain request

Separating the front and back ends leads to cross-domain problems, and my solution is crude.

1.Springboot Controller adds annotations for cross-domain resources

 @CrossOrigin(origins = "*", maxAge = 3600)
Copy the code

Don’t ask me why, I don’t know, but it worked, allowing all cross-domain requests. Ruan God has a detailed article about cross-domain resource sharing CORS, I did not read it carefully.

2. Unified BaseUrl

Vux uses Axios. I know, but I don’t really know. Not knowing how to configure BaseUrl, I used a stupid method: global variables. I know Webpack can assign urls to component production and test environments, but I don’t have the time or energy to study them, so I’ll study them after the project

Create global.js file in config

const BASE_URL ="localhost:8080/"export default{    BASE_URL}Copy the code

Import it from main.js and add it to the Vue global:

import global_ from ". /.. /config/global"Copy the code

Vue.prototype.GLOBAL = global_;Copy the code

It can then be referenced in the component as follows:

this.$http
        .post(this.GLOBAL.BASE_URL+"user/login? id="+this.id+"&password="+this.password)
        .then(function(response) {
          console.log(response.data);
        })        
        .catch(function(error) {
          console.log('error'+error);
        });Copy the code

But, there will be an error during build, I forgot the error content, I searched it, it seems to say that the writing method of global is ES6, it is not correctly resolved, need to use Babel parsing. The solution is to modify the webpack.base.conf.js file

The original configuration:

 module: {
    rules: [{test: /\.vue$/.loader: 'vue-loader'.options: vueLoaderConfig
      },
      {
        test: /\.js$/.loader: 'babel-loader'.include: [resolve('src'), resolve('test')},...Copy the code

Increase the resolve (‘ config/global. Js)

module: {
    rules: [{test: /\.vue$/.loader: 'vue-loader'.options: vueLoaderConfig
      },
      {
        test: /\.js$/.loader: 'babel-loader'.include: [resolve('src'), resolve('test'),resolve('config/global.js')},...Copy the code

Packaged deployment

At the back end, I made a JAR package. Springboot already has its own Tomcat server, so I feel there is no need to make a WAR package and put it in the container.

1. First, I tried to insert the files (static directory, index.html file) in the dist folder of the front-end build into the Resources /static folder of springBoot:

According to Spring Boot’s default configuration for static resource mapping, /index.html should be able to find the index.html file under this directory. But it shows undefined interface and is blocked. SpringMvc interceptor is used in WebConfigurer. So I added

 registry.addResourceHandler("/static/**").addResourceLocations( "classpath:/static/");Copy the code

/staitic/index.html /staitic/index.html /staitic/index.html /staitic/index.html /staitic/index.html /staitic/index.html /staitic/index.html Apk download is blocked, so change the configuration to:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("doc.html")
            .addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/static/**").addResourceLocations( "classpath:/static/");
    registry.addResourceHandler("/app-release.apk").addResourceLocations( "classpath:/static/");
    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
    super.addResourceHandlers(registry);
}Copy the code

2. Use Nginx

Do not use localhost for ajax requests, use IP address directly, download Nginx, modify configuration file:

server { listen 8079; ,, port number... root /front/dist; //dist folder path index index.html index.htm; add_header Access-Control-Allow-Origin"*"; . }Copy the code

Do not double-click nginx.exe. This will cause invalid restart and stop nginx after configuration modification. You need to manually shut down all nginx processes in the task Manager

In the nginx.exe directory, open the command line tool and start/shut down/restart nginx with commands

Start nginx: starts the nginx

Nginx -s reload: Modify the configuration and reload it to take effect

Nginx -s reopen the log file

Nginx -t -c /path/to/nginx.conf Tests whether the nginx configuration file is correct

Close the nginx:

Nginx -s stop: Stops the nginx quickly

Nginx -s quit: Complete and orderly stop nginx

conclusion

At this point, the practice of Vue and Springboot front and back end separation is basically completed, of course, there are many problems and knowledge points need to learn and understand. Because the job regardless of content or technology and these irrelevant, input energy is limited, can only rely on spare time self-study. Please comment on the problems and shortcomings of the architecture. After watching the nuggets for quite a long time, I wrote an article for the first time and found that I had no writing skills in the technical field, haha