Solve the cross-domain problem of Vue+SpringBoot+Shiro

Solve the cross-domain problem of Vue+SpringBoot+Shiro

I believe everyone will encounter this problem when they first start. I have searched a lot on the Internet but it is useless and they are not fully written.

I'll record it here, I hope it will be helpful to everyone

1. Configure Vue front end

Configure proxy information in index.js under config

Note: The cross-domain configuration here is only valid in the development environment. After packaging and deployment, this cross-domain will not work. I have been stuck here for a long time. After the Vue front-end is packaged, it is best to deploy it to nginx. Using nginx can directly solve the cross-domain problem

1. Develop cross-domain configuration

proxyTable: {
'/api': {
target: 'http://xxxx.com', //AddresschangeOrigin: true,
pathRewrite: {
'^/api': ''
  },
 }
},

Configure Ajax proxy request in main.js

var axios = require('axios')
axios.defaults.baseURL = '/api' // Environment

Then when we write the request method, add "/api" before the method. This is based on your configuration name. Write whatever name you have configured.

In this way, our front-end Vue development cross-domain configuration is complete

2. Production cross-domain configuration

First, let's look at the code configuration

I read a lot of articles and information on the Internet, which said to modify this and modify that, but the facts are all the same. . . .

In fact, we only need to configure the proxy information in index.js under config

proxyTable: {
'/api/*': {
target: 'http://domain name', //The production address must add http
changeOrigin: true,
pathRewrite: {
'^/api': '/api'
  },
 }
},

Above, we set the default request path of axios when configuring local cross-domain, and production packaging does not need to be configured

Now our code is configured. Don't change anything else. Then run npm run build and it will be ready.

The rest of the work can be left to nginx. I deployed nginx on the windows service. There are a lot of installation steps on the Internet, so I won’t go into details here.

After we install nginx, we need to do some configuration

1. Delete the contents of the html directory under nginx

2. Copy our Vue package dist to the html directory of nginx,

3. Configure nginx.conf in the config directory under nginx. The configuration content is as follows:

Here is an explanation: the file directory name of the nginx application is changed. We directly install it with nginx-1.xx, similar to this directory. When we configure the root path in the figure above, /n may have compilation problems. I changed it to ProNginx here. You can change it to your favorite name

This is all my nginx configuration

#user nobody;
worker_processes 1;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;


events {
    worker_connections 1024;
}


http {
    include mime.types;
    default_type application/octet-stream;

    #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    # '$status $body_bytes_sent "$http_referer" '
    # '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log logs/access.log main;

    sendfile on;
    #tcp_nopush on;

    #keepalive_timeout 0;
    keepalive_timeout 65;

    #gzip on;

server {
        listen 80;
        server_name front-end service domain name/IP;
        root D:/HWKJ/ProNginx/ProNginx/html/dist/;
        
        location / {
            index index.php index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
            location /api/ {
            #rewrite ^.+api/?(.*)$ /$1 break;
            #include uwsgi_params;
            proxy_pass http://xxxbackgroundxxxx/api/;
            #Solve the problem of obtaining remote IP in springboot}
    }
}

After configuration, we start nginx. Here are some operation commands of nginx

start nginx //Start nginx -s stop // stop is to stop nginx quickly, and may not save relevant information nginx -s quit // quit is to stop nginx in a complete and orderly manner and save relevant information nginx -s reload // When the configuration information is modified, use this command to reload the configuration nginx -s reopen // Reopen the log file nginx -v // View the Nginx version

In this way, our front-end Vue production cross-domain configuration is completed

Next we configure the spring boot background

2. Configure spring boot

If you only have spring boot, then you can configure the information

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.*;


/**
 */
@Configuration
public class MyWebConfigurer implements WebMvcConfigurer {

@Override
   public void addCorsMappings(CorsRegistry registry) {
       registry.addMapping("/**") // Paths that allow cross-domain access.allowCredentials(true) // Whether to send cookies
               .allowedOriginPatterns("*") // Origins allowed for cross-domain access.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") // Allowed request methods.allowedHeaders("*") // Allowed header settings.maxAge(168000); // Pre-check interval}  
}

If your spring boot backend is integrated with shiro, the above configuration will not take effect on shiro's request , and the browser will still prompt cross-domain, so we use the following method to set up cross-domain access

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.*;


/**

  */
@Configuration
public class MyWebConfigurer implements WebMvcConfigurer {
    @Bean
    public FilterRegistrationBean corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        // Allow cookies to be sent across domains config.setAllowCredentials(true);
        // #Allow the URI to submit requests to the server. * means all are allowed. In SpringMVC, if it is set to *, it will automatically be converted to the Origin in the current request header.
        config.addAllowedOriginPattern("*");
        // # Header information allowed to be accessed, * means all config.addAllowedHeader("*");
        // The cache time (in seconds) for pre-check requests. That is, during this time period, the same cross-domain request will not be pre-checked again. config.setMaxAge(18000L);
        // Methods allowed to submit requests, * means all are allowed config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        source.registerCorsConfiguration("/**", config);

        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        // Set the listener priority bean.setOrder(0);

        return bean;
    }
}

This is the end of this article about solving the cross-domain problem of Vue+SpringBoot+Shiro. For more relevant Vue SpringBoot Shiro cross-domain content, 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:
  • Solve the 403 cross-domain problem of Vue calling springboot interface
  • vue+springboot implements CORS cross-domain request of the project
  • Vue+springboot front-end and back-end separation to achieve single sign-on cross-domain problem solution
  • Solve the problem of Vue+springboot cross-domain session+cookie invalidation when separating front-end and back-end
  • Solution to the cross-domain problem of SpringBoot and Vue interaction

<<:  Detailed analysis of MySQL master-slave delay phenomenon and principle

>>:  A brief analysis of the best way to deal with forgotten MySQL 8 passwords

Recommend

Example of how to set up a Linux system to automatically run a script at startup

Preface Hello everyone, I am Liang Xu. At work, w...

CentOS7 installation zabbix 4.0 tutorial (illustration and text)

Disable SeLinux setenforce 0 Permanently closed: ...

MySQL data duplicate checking and deduplication implementation statements

There is a table user, and the fields are id, nic...

MYSQL A question about using character functions to filter data

Problem description: structure: test has two fiel...

JavaScript canvas implements moving the ball following the mouse

This article example shares the specific code of ...

How to start tomcat using jsvc (run as a normal user)

Introduction to jsvc In production, Tomcat should...

Solution to the timeout problem when installing docker-compose with PIP

1: Installation command pip install docker-compos...

Summary of considerations for writing web front-end code

1. It is best to add a sentence like this before t...

How to use border-image to implement text bubble border sample code

During the development activity, I encountered a ...

MySQL 8.0.16 installation and configuration graphic tutorial under macOS

This article shares the installation and configur...

How to monitor mysql using zabbix

Zabbix deployment documentation After zabbix is ​...

How to solve the slow speed of MySQL Like fuzzy query

Question: Although the index has been created, wh...

Detailed explanation on how to get the IP address of a docker container

1. After entering the container cat /etc/hosts It...