SpringBoot interacts with Vue to solve cross-domain problems

Posted by valen53 on Tue, 05 Oct 2021 18:18:47 +0200

Hello, I'm a Grey Ape, a bug-writing ape!

Recently, a separate front-end and back-end personal blog site was developed using springboot+vue integration, so this article summarizes a problem encountered in the development and how to solve cross-domain problems when using Vue and springboot to separate front-end and back-end projects. Share two methods here, one in front-end Vue and the other in back-end springboot.

Browser Homology Policy

Why do cross-domain problems arise? First of all, the browser's homology policy must be understood.

What is the browser's homology policy?Simply put, the protocols, domain names, and ports the browser sends requests need to be consistent with the protocols, domain names, and ports the server receives. This allows interaction to be completed, but it is clearly not possible, especially when developing front-end and back-end separated projects on the same computer. This creates a cross-domain problem..

Here are two ways I can solve cross-domain problems.

1. VUE Front End Configuration Agent Resolves Cross-Domain

(1) Let browsers request cookie s in Vue

First, let's talk about how I found cross-domain problems. I didn't carry my browser's cookies when I sent requests from the front-end browser to the back-end, but that resulted in a failure to validate my browser's requests, so later I used a method to have my browser carry cookies in the http request header each time it sent a request, such asNext:

Write the following code in vue's main.js method:

//Introducing axios dependencies
import axios from 'axios'
//Allow requests to bring cookie s to the browser
axios.defaults.withCredentials=true
Vue.prototype.$axios = axios

This means introducing an axios request, or ajax request, while opening the write credentials, and carrying the cookie only if withCredentials equals true.

(2) Configure proxy in vue to resolve cross-domain issues

Resolving cross-domain issues in vue is actually easier because the first half of the URL must be the same for every request we send from a browser, such as http://localhost:8080/blogs and http://localhost:8080/login, we can extract their same URLs and encapsulate them in axios.defaults.baseURL s so that we can request them every time we request themThe address is abbreviated as'/blogs', which is equivalent to a simple encapsulation of the URL header.

Note: Set axios.defaults.baseURL for Unified Request Path =
"http://localhost:8080"Should be written in axios.js

But when solving cross-domain problems, we should use axios.defaults.baseURL = "http://localhost:8080 Write as axios.defaults.baseURL ='/api'.
This way, each path we request will be preceded by an "/api" form.
This is also the first step:

The first step is to set up a unified access path

Set in axios.js http://localhost:8080"Write as axios.defaults.baseURL ="/api"

Step 2, Configure a cross-domain proxy:

Create a new JS file vue.config.js under the same directory as babel.config.js

Write the following code in it: This code is a proxy configured to solve cross-domain problems. My background server's request connection here is http://localhost:8081 So if you're not, you need to modify it.

/**
 * Solving cross-domain problems
 * @type {{devServer: {proxy: {"/api": {changeOrigin: boolean, pathRewrite: {"^/api": string}, target: string}}, host: string, open: boolean}}}
 */
module.exports = {
    devServer: {
        host: 'localhost',
        open: true, // Open browser automatically
        // Proxy configuration table, where you can configure a specific request proxy to the corresponding API interface
        // For example, proxy'localhost:8080/api/xxx'to'www.example.com/api/xxx'
        proxy: {
            '/api': { // Match all request paths starting with'/api'
                target: 'http://localhost:8081', //Proxy target base path
                // secure: false, //If it is an https interface, this parameter needs to be configured
                changeOrigin: true, // Supports cross-domain
                pathRewrite: { // Rewrite Path: Remove the'/api'at the beginning of the path
                    '^/api': ''
                }
            }
        }
    }
}

Step 3, Test Request

If we are sending a login login request now, the request should read as follows:

this.$axios.post("/login")

2. springboot Backend Configuration Resolves Cross-Domain

To solve cross-domain problems at the back end of the springboot framework, simply add a class, CorsConfig, and let it implement the WebMvcConfigurer interface, with the following code, which is typically copied directly in the development process.


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Solving cross-domain problems
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");

    }
}

The above two ways I solve cross-domain problems, I also find a lot of ways to solve cross-domain problems on the Internet, but they are intricate. After trying and researching, the above two methods were successful for me. At that time, both front-end and back-end were configured.

So the little buddies have different opinions or better ways, welcome to make corrections!

I'm a Grey Ape. See you next time!

Topics: Javascript Spring Boot Vue.js Ajax