Solution to the cross-domain problem of SpringBoot and Vue interaction

Solution to the cross-domain problem of SpringBoot and Vue interaction

Hello, I’m Gray Ape, a programmer who is really good at writing bugs!

Browser Same Origin Policy

Why do cross-domain issues occur? First of all, we must understand a definition, which is the browser's homology policy.

What is the browser's same-origin policy? Simply put, the protocol, domain name, and port used by the browser to send the request must be consistent with the protocol, domain name, and port used by the server to receive the request. This is the only way to complete the interaction, but it is obviously impossible, especially when developing a project with separated front-end and back-end on the same computer, two ports must be used. This creates a cross-domain problem.

Here I share two methods I used to solve cross-domain problems.

1. VUE front-end configuration proxy solves cross-domain

(1) Allow browser requests to carry cookies in Vue

Let me first tell you how I discovered the cross-domain problem. At first, when I sent a request from the front-end browser to the backend, I did not carry the browser's cookies, but this made it impossible to verify the browser's request. So later I used a method to let the browser carry the cookie in the http request header every time it sent a request. The method is as follows:

Write the following code in the main.js method of vue:

//Introduce axios dependency import axios from 'axios'
//Let the request carry the browser's cookie
axios.defaults.withCredentials=true
Vue.prototype.$axios = axios

The above means introducing axios request, that is, ajax request, and enabling writing credentials at the same time. Cookies will be carried only when withCredentials is equal to true.

(2) Configure proxy in Vue to solve cross-domain problems

Solving the cross-domain problem in Vue is actually quite simple, because every time our browser sends a request, the first half of the URL must be the same, such as http://localhost:8080/blogs and http://localhost:8080/login . We can extract their identical URLs and encapsulate them into axios.defaults.baseURL . In this way, we can shorten the request address to “/blogs” every time we make a request, which is equivalent to a simple encapsulation of the URL header.

Note: Set axios.defaults.baseURL =
"http://localhost:8080"
should be written in axios.js

But when solving cross-domain problems, we should write axios.defaults.baseURL = "http://localhost:8080" as axios.defaults.baseURL = “/api” .
In this way, the path of each request will be preceded by “/api” .
This is also the first step:

The first step is to set up a unified access path

In axios.js, set axios.defaults.baseURL = "http://localhost:8080"寫成axios.defaults.baseURL = "/api"

Step 2: Configure cross-domain proxy

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

insert image description here

Write the following code in it: This code is a proxy configured to solve the cross-domain problem. My backend server's request connection is http://localhost:8081, so if yours is not, you need to modify it.

/**
 * Solve cross-domain issues* @type {{devServer: {proxy: {"/api": {changeOrigin: boolean, pathRewrite: {"^/api": string}, target: string}}, host: string, open: boolean}}}
 */
module.exports = {
    devServer: {
        host: 'localhost',
        open: true, // Automatically open the browser // Proxy configuration table, where you can configure specific request proxies 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', // Base path of the proxy target//secure: false, // If it is an https interface, you need to configure this parameterchangeOrigin: true, // Support cross-domain pathRewrite: { // Rewrite path: remove the '/api' at the beginning of the path
                    '^/api': ''
                }
            }
        }
    }
}

Step 3: Test Request

If we want to send a login request now, the request should be written like this:

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

2. Springboot backend configuration solves cross-domain

To solve the cross-domain problem in the backend of the springboot framework, you only need to add a class CorsConfig and let it implement the WebMvcConfigurer interface. The code is as follows. Generally, you can just copy the code during development.

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

/**
 * Solve cross-domain issues */
@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 are the two methods I used to solve cross-domain problems. I also found many methods to solve cross-domain problems on the Internet, but they were complicated. After trying and researching by myself, the above two methods were successfully tested by me. Both the front-end and back-end were configured at that time.

So if you have different opinions or better methods, please feel free to point them out!

I am Gray Ape, see you next time!

Please add a description of the image

This is the end of this article about the solution to the cross-domain problem of SpringBoot and Vue interaction. For more relevant content about SpringBoot and Vue interaction, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • SpringBoot+Spring Security cannot achieve cross-domain solution
  • Analysis and modification of cross-domain issues in Springboot upgrade to 2.4.0
  • Three solutions to Springboot cross-domain problems
  • Analysis of solutions to cross-domain problems in vue+springboot front-end and back-end separation projects
  • Springboot cross-domain problem solution
  • SpringBoot cross-domain solution
  • Several cross-domain solutions for Spring

<<:  Recommend several MySQL related tools

>>:  Commonly used HTML format tags_Powernode Java Academy

Recommend

Zabbix redis automatic port discovery script returns json format

When we perform automatic discovery, there is alw...

React sample code to implement login form

As a Vue user, it's time to expand React. Fro...

Vue realizes the whole process of slider drag verification function

Rendering Define the skeleton, write HTML and CSS...

Two ways to export csv in win10 mysql

There are two ways to export csv in win10. The fi...

Understanding v-bind in vue

Table of contents 1. Analysis of key source code ...

Vue implements pull-down to load more

Developers familiar with Element-UI may have had ...

Vue.js cloud storage realizes image upload function

Preface Tip: The following is the main content of...

Web2.0: Causes and Solutions of Information Overload

<br />Information duplication, information o...

How to automatically number the results of MYSQL query data

Preface In fact, I have never encountered this ki...

Windows 10 + mysql 8.0.11 zip installation tutorial detailed

Prepare: MySQL 8.0 Windows zip package download a...

How to forget the root password in Mysql8.0.13 under Windows 10 system

1. First stop the mysql service As an administrat...

Complete steps to build NFS file sharing storage service in CentOS 7

Preface NFS (Network File System) means network f...