0

Here's my code:

const dummydata = {
  param1: 72766,
  param2: 'ELS'
}

var foo = JSON.stringify(dummydata)

let headers = new Headers();
headers.append('content-type', 'application/json');

this.http.post(url, foo, { headers: headers }).map(res => res.json()).subscribe(
  () => { alert('Success'); }
);

For some reason there's no data going to the server as form-datain Request Payload and the type is getting converted to OPTIONS instead of POST On the other hand if I remove, headers, then the form-data is going but another error occurs:

415 Unsupported Media Type

UPDATE: JQuery Ajax is working

UPDATE2: Already tried this:

let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
ABGR
  • 4,631
  • 4
  • 27
  • 49
  • 2
    When you do an HTTP request, Angular will always do an OPTIONS to see if it can reach the endpoint. If your option is in error, then your POST won't work. Here, it's a server issue, not accepting the media type. So either you change your data, or you change how your server treats the data. –  Jun 09 '17 at 12:41
  • @trichetriche I tried changing data in different ways. Pretty much doing this the whole day today. No luck so far. The thing is if I try jQuery Ajax, it works – ABGR Jun 09 '17 at 12:46
  • @trichetriche that is not correct, OPTIONS requests are made by the browser not by Angular. They're usually made when user does a cross-domain request, check this for more info: https://stackoverflow.com/questions/27915191/how-does-the-chrome-browser-decide-when-to-send-options – eko Jun 09 '17 at 12:47
  • My mistake, but the idea is there. Thanks for the heads up –  Jun 09 '17 at 12:53

5 Answers5

1

You can try this:

const dummydata = {
 param1: 72766,
 param2: 'ELS'
}

import {Headers, RequestOptions} from 'angular2/http';


let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

 this.http.post(url, dummydata, options).map(res=>res.json()).subscribe(
        () => { alert('Success'); }
    );
Ketan Akbari
  • 10,837
  • 5
  • 31
  • 51
  • Same. The type gets converted to 'OPTIONS' and Request payload doesn't contain anything. So no response from the server – ABGR Jun 09 '17 at 12:53
  • Looks like you might have some [cors](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) issue, plz make sure URL you are trying to access handle it – Ajhar Shaikh Jun 09 '17 at 12:58
  • if so,you can use plugins: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en – Ketan Akbari Jun 09 '17 at 13:01
  • @KetanAkbari Thank that works. But why was it working with JQuery ajax but not with angular 2 http. Another thing is this probably might not be feasible solution – ABGR Jun 09 '17 at 13:20
  • @Ajax yup probably that was the issue. Any idea as to why it was working with JQuery ajax but not with angular 2 http – ABGR Jun 09 '17 at 13:23
  • @KetanAkbari Now two requests are getting made. On the usual one which was occurring earlier and then the other probably due to this extension which is fetching response – ABGR Jun 09 '17 at 13:29
0

Angular way to do post request.

const dummydata= {param1:72766,
        param2:'ELS'}

    var foo=    JSON.stringify(dummydata);

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });


 this.http.post(url, foo,{headers: headers} ).map(res=>res.json()).subscribe(
            () => { alert('Success'); }
        );

for more info check this link https://angular.io/docs/ts/latest/guide/server-communication.html

CharanRoot
  • 6,181
  • 2
  • 27
  • 45
0

You have to check if your server support OPTIONS request, if not you need to add These lines in your htaccess file

Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type" Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

oubchid
  • 591
  • 1
  • 4
  • 6
  • htaccess is used only by apache (and according to my knowledge it is used in older versions). Therefore your answer is inadequate although it is true as principle. – Jan Giacomelli Jun 09 '17 at 20:45
0

It should be CORS problem.
When you make CORS requests from browser (call to different URL then the host of javascript files) it will automatically make OPTIONS request before any other request is made. If response is appropriate it will make GET, POST, DELETE, PUT request as written in code.
Example:

  1. You want to make POST request to myserver.com/add-book/
  2. Browser will make OPTIONS request to myserver.com/add-book/
  3. If response to OPTIONS contains requested headers etc. (e.g. Allowed-Methods header) POST request will be executed

Therefore you need to have OPTIONS request enabled on your server and REST API. If you are using authentication with JWT you need to mark OPTIONS request as safe - JWT don't need to be in headers of your request.
More about OPTIONS request

Jan Giacomelli
  • 1,299
  • 11
  • 23
0

I found a better way to tackle this CORS issue by configuring a proxy for the API calls with Angular CLI:

I created a proxy.conf.json:

{
  "/API": {
    "target": "http://myserver.com",
    "secure": false
  },
  "/API2":{
    "target": "http://myserver.com",
    "secure": false
  }
}

Then in package.json under scripts:

"start": "ng serve --proxy-config proxy.conf.json",

Now for calling the APIs simply provide the URLs like "/API/getData" and CLI will automatically redirect to the http://myserver.com/API/getData

ABGR
  • 4,631
  • 4
  • 27
  • 49