Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a JSONP POST request in angular?

The $http.jsonp method described in the official documentation seems to always perform get requests: http://docs.angularjs.org/api/ng.$http#methods_jsonp.

I have tried setting the config option to 'POST' but it still sends a GET:

$http.jsonp('/api/new?callback=JSON_CALLBACK', {method: 'POST'});

I have also tried setting a data argument in the hope that angular would switch to a POST:

$http.jsonp('/api/new?callback=JSON_CALLBACK', {data: {stuff: true}});

But it still doesn't :)

As for making a post like this:

$http.post('/api/new?callback=JSON_CALLBACK')

It does make a POST obviously but doesn't do the angular magic thingy with the JSON_CALLBACK and produces the following JS error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxx.yyy.zzz' is therefore not allowed access.

(The API is not on the same server as the app, that's the point of JSONP).

Google was most unhelpful on this issue and reading through angular's sources is not the easiest task. So how can I make a JSONP POST request with angular?

like image 620
djfm Avatar asked Jan 25 '14 14:01

djfm


People also ask

Can Angular accept POST request?

It is a bit awkward requirement since Angular is JavaScript framework and It does not accept post request because post request needs to be handled at server side only not at client side.

What is JSONP in Angular?

JSONP is a method of performing API requests which go around the issue of CORS . This is a security measure implemented in all browsers that stops you from using an API in a potentially unsolicited way and most API s, including the iTunes API , are protected by it.

What does JSONP use for request?

JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.


1 Answers

You cannot make a POST request using JSON-P (with or without Angular)

A JSON-P request works by generating a <script> element with a src attribute. This will always trigger a GET request.


If you want to make a cross-domain POST request with JavaScript then you must use either XMLHttpRequest (and have the server supply suitable access control headers as per the CORS specification) or proxy the request through the server hosting the page.

like image 179
Quentin Avatar answered Oct 13 '22 15:10

Quentin