springboot和vue前后端分离跨域配置

1,后端配置

package org.lht.boot.security.server.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 配置跨域
 *
 * @author lht
 * @date 2020-07-02
 */
@Configuration
public class WebCrossDomainConfiguration extends WebMvcConfigurerAdapter {
    
    

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

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
    
    
        configurer.setTaskExecutor(new ConcurrentTaskExecutor(threadPoolTaskExecutor()));
        configurer.setDefaultTimeout(30000);
    }

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
    
    
        ThreadPoolTaskExecutor t = new ThreadPoolTaskExecutor();
        t.setCorePoolSize(10);
        t.setMaxPoolSize(100);
        t.setQueueCapacity(20);
        t.setThreadNamePrefix("TaskExecutor-Thread-");
        return t;
    }

}

2,前端配置

const service = axios.create({
    
    
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    // easy-mock服务挂了,暂时不使用了
    baseURL: 'http://localhost:8080/',
    timeout: 5000,
    withCredentials: true//这里不配置继承Springsecurity情况下登陆sessionId不一致

3,如果项目是springsecurity项目,还需要加入如下配置
后端自定义WebSecurityConfigurerAdapter,加入如下代码

      http
      .cors()
      .and()
      .csrf()
      .disable()
      .authorizeRequests()
      .requestMatchers(CorsUtils::isPreFlightRequest)
      .permitAll()

猜你喜欢

转载自blog.csdn.net/weixin_38019299/article/details/107193017