Angular Spring Boot:重定向错误:在飞行前响应中Access-Control-Allow-Headers不允许请求标头字段Content-Type

时间:2018-07-31 09:56:00

标签: java spring angular spring-boot cors

我在前端使用Angular 6,在后端使用Java Spring Boot。

我希望我的登录页面向服务器发出请求。服务器重定向到仪表板页面。

我有http://localhost:4200/login个角度页面,该页面向服务器http://localhost:8080/login发出了POST请求

.ts文件包含:

onLoginClickPost() {
  console.log('redirect request clicked');
  this.data.getUserInfoPost().subscribe(
    data => {
      console.log(data);
      this.userInfo = data;
    }
  );
}

getUserInfoPost() {
    return this.http.post('http://localhost:8080/login', {nextUrl: 'http://localhost:4200/dashboard'});
}

服务器具有@RestController,其方法映射到传入的POST请求,该方法应重定向到http://localhost:4200/dashboard

@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<?> login_post(@RequestBody LoginReqPostParam payload) {

    HttpHeaders headers = new HttpHeaders();

    try {
        headers.setLocation(new URI(payload.getNextUrl()));
        headers.add("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
    } catch (URISyntaxException e) {
        logger.error("URI Exception: ", e);
        e.printStackTrace();
    }

    return new ResponseEntity<>(headers, HttpStatus.FOUND);
}

LoginReqPostParam是一个简单的类,将传入的JSON有效负载作为对象。

登录角度页面能够向服务器发出POST请求。现在在服务器上,从服务器返回ResponseEntity之后,在浏览器控制台中出现以下错误:

  

无法加载http://localhost:4200/dashboard请求标头字段   Content-Type不允许通过Access-Control-Allow-Header   飞行前响应。

enter image description here

如何重定向到http://localhost:4200/dashboard页?我需要向角度仪表板组件文件中添加一些内容吗?

2 个答案:

答案 0 :(得分:0)

您正在使用@CrossOrigin进行POST请求,但是Angular(正在开发中)正在使用OPTIONS发送 Preflight请求

我建议您使用允许所有来源的开发配置文件(您必须在Bean中为这些配置文件创建自定义过滤器)

答案 1 :(得分:-1)

使用Allow-Control-Allow-Origin:* Google chrome扩展名。 并启用跨源资源共享 https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en