微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

遇到错误-在运行Angular + Spring Boot应用程序时获取http:// localhost:8080 / hello / variable / user net :: ERR_FAILED

如何解决遇到错误-在运行Angular + Spring Boot应用程序时获取http:// localhost:8080 / hello / variable / user net :: ERR_FAILED

在localhost中通过禁用csrf()并启用OPTION请求而在Angular + Spring引导应用程序中运行时出现以下错误

错误-CORS策略已阻止从来源'http:// localhost:4200'访问'http:// localhost:8080 / hello / variable / paraan'处的XMLHttpRequest:否'Access-Control-Allow-来源的标头出现在请求的资源上。

获取http:// localhost:8080 / hello / variable / user net :: ERR_Failed zone-evergreen.js:2845

角度 welcome-data.service.ts

executeHelloWorldBeanServicePathVarible(name)
  {
    let basicAuthHeaderString=this.createBasicAuthenticationHttpHeader();
    let headers=new HttpHeaders({
      Authorization:basicAuthHeaderString
    })
   
    return this.http.get<helloWorldBean>
    (`http://localhost:8080/hello/variable/${name}`,{headers});
  }

  createBasicAuthenticationHttpHeader(){
    let username='user'
    let password='dummy'
    
    let basicAuthHeaderString='Basic' + window.btoa(username + ':' + password);
    
    return basicAuthHeaderString;
    
      } 

SpringSecurityConfigurationBasicAuth.java

package com.practice.rest.webservices.restfulwebservices.basic.auth;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.bind.annotation.CrossOrigin;

@Configuration
@EnableWebSecurity 
  public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter{
  
  @Override
  protected void configure(HttpSecurity http) throws Exception {
  
  http
  .csrf().disable()
  .authorizeRequests()
  .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
  .anyRequest().authenticated() 
  .and() 
  //.formLogin().and() 
  .httpBasic(); 
  }
  
  }
 

编辑了SpringSecurityConfigurationBasicAuth.java

package com.practice.rest.webservices.restfulwebservices.basic.auth;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter{
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .csrf().disable()   
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .anyRequest().authenticated()
                .and()
            //.formLogin().and()
            .httpBasic();
    }
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin(CorsConfiguration.ALL);
        config.addAllowedHeader("*");
        config.addExposedHeader("Authorization");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        source.registerCorsConfiguration("/**",config);
        return new CorsFilter(source);
    }
}

解决方法

您必须使用 ageRateChart.xAxis.apply { position = XAxisPosition.BOTTOM setDrawGridLines(false) granularity = 1f valueFormatter = object : ValueFormatter() { override fun getAxisLabel(value: Float,axis: AxisBase?): String { return (value * 10 + 10).toString() + "대" } } } 注释或Java配置启用CORS支持。

有关更多信息,请访问此链接:

CORS support in Spring Framework

您可以将带注释的处理程序方法添加到@RequestMapping中。 @CrossOrigin批注以在其上启用CORS(默认情况下, @CrossOrigin允许所有来源和HTTP方法中指定的 @RequestMapping注释):

CrossOrigin

还可以为整个控制器启用CORS:

@RestController
@RequestMapping("/account")
public class AccountController {

    @CrossOrigin
    @GetMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @DeleteMapping("/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

,

只需添加CorsFilter bean

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin(CorsConfiguration.ALL);
        config.addAllowedHeader("*");
        config.addExposedHeader("Authorization");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        source.registerCorsConfiguration("/**",config);
        return new CorsFilter(source);
    }
,

将此添加到您的代码中。

@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http.headers()
        .referrerPolicy(ReferrerPolicy.NO_REFERRER);
    return http.build();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。