Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Http POST not working

I hope everyone is doing great. I've recently started working with angular 4.4, i've been trying to post data to my api server, but unfortunately it's not working. I've spent like 2 days on it but still no success. And have already tried 6-7 article even from angular.io. I've tried both Http and Httpclient modules but nothing seems to be working.

The problem is, whenever i try to post data to my server, Angular makes http OPTIONS type request instead of POST.

this.http.post('http://myapiserver.com', {email: '[email protected]'}).subscribe(
    res => {
        const response = res.text();
    }
);

And i've also tried to send custom options with the request but still no success.

const headers = new Headers({ 'Content-Type': 'x-www-form-urlencoded' });
const options = new RequestOptions({ headers: headers });
options.method = RequestMethod.Post;
options.body = {name: 'Adam Smith'};
//options.body = JSON.stringify({name: 'Adam Smith'}); // i also tried this
//options.body = 'param1=something&param2=somethingelse'; // i also tried this

I was using ASP.NET core 2.0, but since it wasn't working i also tried simple php code, Here is the server side code for php. And it's also not working.

<?php
print_r($_POST);
?>

Note: Cors are also enabled on server. Plus I also tried simple get request and its working perfectly fine.

I'll really appreciate some help.

Thanks in advance

like image 338
Osama Sheikh Avatar asked Oct 12 '17 14:10

Osama Sheikh


1 Answers

I solved it by setting the Content-Type to application/x-www-form-urlencoded:

  const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
  const options = new RequestOptions({ headers: headers });
  const params = new URLSearchParams();
  params.append('mypostField', 'myFieldValue');
  http.post('myapiendpoint.com', params, options).subscribe();
like image 74
Osama Sheikh Avatar answered Oct 20 '22 12:10

Osama Sheikh