Я столкнулся с большой проблемой при попытке получить доступ к моему Rest API, построенному с помощью Springboot из моего внешнего интерфейса VueJS.
Backend-URL = http: // локальный: 8080
Frontend-URL = http: // локальный: 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 {
...
NewFile: 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




Создайте файл vue.config.js в корневом каталоге VueJS, если он не существует, и добавьте его
// 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.
Надеюсь, это может вам немного помочь, если еще не решено
Для получения дополнительной информации смотрите здесь