简体   繁体   中英

Angular Spring Boot: Redirection error: Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response

I'm using Angular 6 in the frontend and Java Spring Boot in the backend.

I want my login page to make request to server. Server redirects to dashboard page.

I have http://localhost:4200/login angular page which makes a POST request to server http://localhost:8080/login

The .ts file contains:

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'});
}

The server has @RestController with a method mapping to incoming POST request, which should redirect to 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 is a simple class to have incoming JSON payload as object.

The login angular page is able to make POST request to the server. Now at the server, after returning the ResponseEntity from server, I'm getting following error in browser console:

Failed to load http://localhost:4200/dashboard : Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

在此处输入图片说明

How do I redirect to http://localhost:4200/dashboard page? Do I need to add something to angular dashboard component files?

You are using @CrossOrigin for POST request but Angular (in development) is sending a Preflight request using OPTIONS.

I recommend you to use a development profile that permit all origins (you must create a custom filter in a Bean for these profile)

Use Allow-Control-Allow-Origin: * extension for google chrome. And enable cross origin resource sharing https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM