通过Angular 2和JSON将对象发送到Spring-Boot的RestController

时间:2016-09-30 18:49:20

标签: angular spring-boot

现在我正在使用H2数据库,想要注册用户并在数据库中查看。

(BackEnd模块)Spring-Boot在端口8080上运行,Angular 2(FrontEnd Module)在3000上运行。

(FRONTEND)

@Injectable()
export class RegisterService {

    constructor (private http:Http) { }

    sendUser (newUser: RegisterModel) {
        let url = "http://localhost:8080/user/register";
       // let header = new Headers({'Content-Type': 'application/json'});

        return this.http.post(url, JSON.stringify(newUser)); //, {headers: header}
    }
}

RegisterModel

export class RegisterModel{
    public userId: number;
    public firstName: string;
    public lastName: string;
    public userName: string;
    public password: string;
    public passwordCheck:string;
    public created: Date;
}

RegisterComponet

@Component ({
    moduleId: module.id,
    selector: 'register',
    templateUrl: './register.html'
})
export class RegisterComponent {

    newUser: RegisterModel = new RegisterModel();

    constructor (private registerService: RegisterService){

    }

    onSubmit() {
        this.registerService.sendUser(this.newUser).subscribe(
            data => {

                this.newUser = new RegisterModel();
            },
            error => console.log(error)
        );
    }
}

(BACKEND)

    @RestController("/user")
public class UserController {

@Autowired
    UserService userService;

@RequestMapping(value = "/register", method = RequestMethod.POST)
    public User registerUser(@RequestBody User user){

        System.out.println("YAY-----------"+user.getFirstName());
        return userService.save(user);
    }

CORS过滤器

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); // you USUALLY want this
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

@Bean
  public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/").allowedOrigins("http://localhost:3000");
      }
    };
  }
}

这是我的目录:

enter image description here

完整目录:

enter image description here

我在控制台中遇到的错误:

enter image description here

我查看帖子回复,这就是我得到的:

enter image description here

git repo

GIT LINK

------------------ UPDATE 1 -----------------------

我将我的CorsConfig类更新为:

@Configuration
public class CorsConfig {

  @Bean
  public CorsFilter corsFilter() {

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(false); //updated to false
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("POST");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
  }

  @Bean
  public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/").allowedOrigins("http://localhost:3000");
      }
    };
  }

}

控制台出错:

XMLHttpRequest cannot load http://localhost:8080/user/register. Response for preflight is invalid (redirect)

这是我通过Google Chrome插件

使用Advanced REST client时获得的结果

enter image description here

我的git repo已使用我当前的代码更新。

一旦我能够使用它,我计划使用弹簧安全。

2 个答案:

答案 0 :(得分:0)

您需要在spring boot app中添加CORS过滤器以允许跨浏览器请求。

答案 1 :(得分:0)

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest)req;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Allow-Headers", "origin, x-requested-with, accept, Authorization, Content-Type");
    response.setHeader("Access-Control-Max-Age", "3600");
    if (!request.getMethod().equals("OPTIONS")) {
      try {
        chain.doFilter(req, res);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ServletException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    } 
  }

  public void init(FilterConfig filterConfig) {}

  public void destroy() {}

}

写下以下

的过滤器
`@Bean
public CorsFilter corsFilter() {

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(false); //updated to false
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);

}`