VueJS和SpringBoot跨域错误

时间:2018-07-17 14:23:10

标签: java spring-boot spring-security vuejs2 axios

当我尝试从我的VueJS前端使用Springboot构建的Rest API时,我遇到了一个大问题。

后端URL = http://localhost:8080
Frontend-URL = http://localhost:8081

在main.js文件中,我为axios添加了以下默认值:

axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
axios.defaults.headers.common['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept';
axios.defaults.withCredentials = true;
axios.defaults.crossDomain = true;

在后端站点上,我添加了以下条目:

所有控制器

@CrossOrigin(origins = "http://localhost:8081")
@RestController
public class ControllerName {
...

新文件:DevelopmentWebSecurityConfigurerAdapter(与主要方法相同的软件包)

package de.my.server;

import java.util.Arrays;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class DevelopmentWebSecurityConfigurerAdapter extends WebMvcConfigurerAdapter {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://locahost:8081"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    protected void configure(HttpSecurity http) throws Exception {

        //http.csrf().disable();
        http
        .cors()
        .and()
        .csrf().disable()
        .anonymous().disable()
        .authorizeRequests()
        .antMatchers("/api").permitAll()
        .antMatchers(HttpMethod.OPTIONS, "/**").permitAll();

    }
}

新过滤器“ CorsFilter”(只需将Java文件添加到与主要方法相同的包中)

package de.my.server;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Component
public class CorsFilter implements Filter {

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request= (HttpServletRequest) servletRequest;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "false");
        response.setIntHeader("Access-Control-Max-Age", 3600);
        filterChain.doFilter(servletRequest, servletResponse);
    }


    public void init(FilterConfig filterConfig) {}

    public void destroy() {}
}

直到现在什么都不起作用...
有人提示我如何访问我的api吗?

亲切的问候
tschaefermedia

1 个答案:

答案 0 :(得分:0)

在您的VueJS根目录中创建一个vue.config.js文件(如果不存在)并将其添加

// vue.config.js
module.exports = {
  // proxy all webpack dev-server requests starting with /api
  // to our Spring Boot backend (localhost:8088) using http-proxy-middleware
  // see https://cli.vuejs.org/config/#devserver-proxy
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:8088',
        ws: true,
        changeOrigin: true
      },
      '/fileUpload': {
        target: 'http://localhost:8088',
        ws: true,
        changeOrigin: true
      }
    }
  },
  // Change build paths to make them Maven compatible
  // see https://cli.vuejs.org/config/
  outputDir: 'target/dist',
  assetsDir: 'static'
}

对于我来说,所有对“ / api”和“ / fileUpload”的请求都转发到我的Spring Java Backend

我希望这可以对您有所帮助

有关更多信息,请查看here