0

I have jquery ajax query:

var data2 = "data"
var ajaxOptions2 = {
    type: "post",
    url: "http://localhost:8050/adapter/interface",
    data: data2,
    dataType: "json",
    success: onSuccess,
    error: onError,
    processData: false,
    contentType: "application/json; charset=UTF-8"
};
$.ajax(ajaxOptions2);

and this post request is working properly

I tried to rewrote this to the angular2 http.post:

let bodyString = "data";
let headers = new Headers({ 'dataType': 'json', 'contentType': 'application/json; charset=UTF-8' });
let options = new RequestOptions({ headers: headers, method: RequestMethod.Post});
that.http.post(that.url, bodyString, options)
    .map(that.extractData)
    .catch(that.handleError)
    .subscribe(data => { console.log("test")});

but http.post is returning error:

XMLHttpRequest cannot load http://localhost:8050/adapter/interface. Request header field dataType is not allowed by Access-Control-Allow-Headers in preflight response.

Can you tell why why jquery ajax is working but my http.post dont?

szpic
  • 4,346
  • 15
  • 54
  • 85
  • 1
    This post should help you: https://stackoverflow.com/a/25727411/6053654 – P.S. Sep 17 '17 at 14:04
  • 1
    They clearly aren't the same, if one is working and the other isn't. jQuery's `dataType` isn't a header, it's a setting that just tells jQuery to parse the returned string as JSON, it's never sent to the server. – adeneo Sep 17 '17 at 14:09

1 Answers1

2

Well the problem is exactly what the error message is stating. In your post request you are setting the header "dataType" which obviously isn't allowed by the server for the POST or OPTIONS request. You are not setting this header in your ajax request. If you want to make it work you either have to remove the header or re-configure your server in order to accept this header instead.

Patrick Kelleter
  • 2,631
  • 1
  • 13
  • 19