我的问题是,每次我向服务器提出请求时,我都会得到一个CORS错误。我尝试过从前端容器向服务器发出curl请求,它们在同一个网络上,一切正常,如果我在本地运行容器,也没有问题。
以下是我的设置:
I在nginx.conf中没有改变任何东西
我的供词取代了default.conf
server {
listen 80;
sendfile on;
default_type application/octet-stream;
gzip on;
gzip_http_version 1.1;
gzip_disable "MSIE [1-6]\.";
gzip_min_length 256;
gzip_vary on;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
gzip_comp_level 9;
root /usr/share/nginx/html;
location / {
try_files $uri $uri/ /index.html =404;
}
}
docker-compose
version: "3.5"
services:
backend:
image: spring_backend
container_name: spring
build:
context: ./
expose:
- 8080
restart: always
networks:
- reverse-proxy
frontend:
image: angular_frontend
container_name: angular
build: https://github.com/some_repo/frontend.git
ports:
- "80:80"
restart: always
networks:
- reverse-proxy
networks:
reverse-proxy:
name: reverse-proxy
角环境
export const environment = {
url: 'http://spring:8080/',
production: true,
};
后端配置
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final PersonDetailsService personDetailsService;
private final JWTFilter jwtFilter;
@Autowired
public SecurityConfig(PersonDetailsService personDetailsService, JWTFilter jwtFilter){
this.personDetailsService = personDetailsService;
this.jwtFilter = jwtFilter;
}
@SneakyThrows(Exception.class)
protected void configure(HttpSecurity http) {
http
.csrf().disable()
.cors().configurationSource(corsConfigurationSource())
.and()
.authorizeRequests().antMatchers("/login","/register").permitAll()
.anyRequest().hasAnyRole("USER")
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
}
@SneakyThrows(Exception.class)
protected void configure(AuthenticationManagerBuilder auth) {
auth.userDetailsService(personDetailsService);
}
@Bean
public PasswordEncoder getPasswordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
@SneakyThrows(Exception.class)
public AuthenticationManager authenticationManagerBean() {
return super.authenticationManagerBean();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.addExposedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
今天,我决定通过邮递员提出一个请求,注意到nginx返回给我一个405错误,spring服务器没有收到请求。使用Mozilla请求根本不发送,只返回一个cors错误
发布于 2022-09-22 06:56:44
CORS
都是关于后端问题的。
基本上,可以通过将Access-Control-Allow-Origin *
添加到服务器配置来解决这个问题,以便其他网站可以使用您的服务。
nginx.conf
server {
...
add_header Access-Control-Allow-Origin *;
...
}
https://stackoverflow.com/questions/73807960
复制相似问题