Build front-end vue, connect front-end and back-end

Foreword In the
previous blog, we created our own backend, so in a situation based on the separation of frontend and backend, what we need to do is to connect the frontend and backend.
1. First of all, we have to create our own vue program, so here I default everyone has set up their own vue environment, create directly!

In your directory, hold down shift and right click on "open powershell here", then

vue init webpack +项目名字

Then the name, and then according to my needs, I clicked yes on the install router, and clicked nowhere else
after our operation, vue's scaffolding project was built.

In your terminal

npm install

This command, then the name
npm run dev
, and then click to run your vue file!

Then we talk about springboot cross-domain, create a tool package under com.example.demo in your springboot backend, and then create a cors file,

Then directly copy my code:

package com.example.demo.tool;

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 解决跨域问题
 * @author chj
 * */
@Configuration
public class Cors {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        /*是否允许请求带有验证信息*/
        corsConfiguration.setAllowCredentials(true);
        /*允许访问的客户端域名*/
        corsConfiguration.addAllowedOrigin("*");
        /*允许服务端访问的客户端请求头*/
        corsConfiguration.addAllowedHeader("*");
        /*允许访问的方法名,GET POST等*/
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

So that your front-end project can access the background interface, then talk about vue axios to access the springboot interface

npm install axios

Use this command, then import in vue. Insert picture description here
Then, in your created, call axios.

  created () {
    axios({
      method: 'post',
      url: 'http://localhost:8080/'
    }).then(res => {
      console.log(res)
    })
  }

By the way, you need to configure the front-end port in your vue scaffolding
, change the port to 8081 in the index.js file in the config folder, then open your browser and enter http: // localhost: 8081

Published 20 original articles · Liked5 · Visits2082

Guess you like

Origin blog.csdn.net/qq_42859887/article/details/97394172