【问题标题】:Java : Cannot send POST request to backend with Angular 5Java:无法使用 Angular 5 向后端发送 POST 请求
【发布时间】:2019-06-04 04:06:20
【问题描述】:

我需要你的帮助。 我认为问题出在 Spring Security 上。 我有一个基于 Spring Boot 的后端,前端基于 Angular 5。 当我尝试向后端发送发布请求时,我遇到了这个问题:

从源“http://localhost:4200”访问“http://localhost:8080/administrateurs”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。

RestController :

package smart.syndic.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import smart.syndic.dao.AdministrateursRepository;
import smart.syndic.entities.Administrateurs;

@RestController
@CrossOrigin("*")
public class AdministrateursRestController 
{
    @Autowired
    private AdministrateursRepository repository;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;



    @RequestMapping(value="/administrateurs", method=RequestMethod.POST)
    public Administrateurs postOne(@RequestBody Administrateurs s)
    {
        String password = s.getPassword();
        String encryptedPassword = bCryptPasswordEncoder
            .encode(password);
        s.setPassword(encryptedPassword);
        return repository.save(s);
    }



 }

Spring Security 的SecurityConfig 类:

package smart.syndic.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication
.builders.AuthenticationManagerBuilder;
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.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{   

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws 
    Exception 
    {   
        auth.inMemoryAuthentication()
        .withUser("admin").password("1234")
        .roles("ADMIN");
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder()
{
    return new BCryptPasswordEncoder();
}


@Override
protected void configure(HttpSecurity http) throws Exception 
{
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/login/**").permitAll();
    http.formLogin().loginPage("/login")
    .and().exceptionHandling().accessDeniedPage("/forbidden");
    http.authorizeRequests().anyRequest().authenticated();

    //When i remove this code it's works 
    }
}

角度服务:

import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders, HttpParams, HttpRequest} from 
"@angular/common/http";

@Injectable()
 export class LoginService
{
  host:any = "http://localhost:8080/";

 constructor(private http:HttpClient)
{

}

 ajouterAdministrateurs(model:any)
{
    return this.http.post(this.host + "administrateurs", model);
}

谢谢。

【问题讨论】:

  • @RequestMapping(value="/administrateurs", method=RequestMethod.POST) public Administrateurs postOne(@RequestBody Administrateurs administrateurs) { 我的猜测。
  • 试试 @CrossOrigin(origins = "*")
  • @MM,我试过了,又是同样的错误
  • 当您的 spring rest 请求未正确连接时,有时会发生这种情况 ------------ 您是否在 postman 中测试过您的 rest API
  • @harkeshkumar 我在尝试向 /administrateurs 发送请求时使用邮递员进行了测试,它给了我这个错误:{ "timestamp": 1547036119354, "status": 405, "error": "Method不允许”,“异常”:“org.springframework.web.HttpRequestMethodNotSupportedException”,“消息”:“不支持请求方法'GET'”,“路径”:“/login”}

标签: java angular spring-boot


【解决方案1】:

希望这会有所帮助。

 public ajouterAdministrateurs(model: any) {
  const headers = new HttpHeaders({
   "Content-Type": "application/json",
   Authorization: "Basic " + btoa("username:password") //add your username and password of spring security
  });
  return this.http.post(this.host, model, {
   headers
  });
 }

【讨论】:

    【解决方案2】:

    在你的 SecurityConfig 类中添加这个 bean:

      @Bean
      public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ImmutableList.of("*"));
        configuration.setAllowedMethods(ImmutableList.of("HEAD",
                "GET", "POST", "PUT", "DELETE", "PATCH","OPTIONS"));
        // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
        configuration.setAllowCredentials(true);
        // setAllowedHeaders is important! Without it, OPTIONS preflight request
        // will fail with 403 Invalid CORS request
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    

    您将需要这些导入:

    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.CorsConfigurationSource;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-29
      • 2018-09-11
      • 2018-08-04
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 2013-03-09
      • 1970-01-01
      相关资源
      最近更新 更多