How to make a JSONP POST request in angular? - javascript

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?

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.

Related

Getting OG data impossible because of CORB

I'm trying to scrape OG data using open-graph-scraper and Vue.js, but it gets blocked because of CORB in Chrome. It is working fine for scripts I run using Node, but is there a work around for this problem or another to get OG data from an input URL?
Cross-Origin Read Blocking (CORB) blocked cross-origin response SOME-INPUT-URL with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.
CORB is a standard that is based around the idea
"what I asked for is what I received"
if you are troubleshooting CORB errors in chrome it means that your request method is being responded to with either no content type or a content type that does not correspond to your method of request.
in a 3rd party API what I would recommend is using a tool like postman (unaffiliated) to inspect the incoming content type in the response headers. Once you know the content-type header of the call then tweak your request method in an attempt to match the expected output. Many API's use poorly implemented frameworks so just because the response is well formed JSON doesn't mean that the header will say JSON. I often see json outputs where the headers are 'text/plain'.
If this doesn't work, for example some api's fail to respond with content headers at all
- another method would be to use an intermediary call to make the request. For example using a combination of the AWS API gateway and a AWS Lambda function you can create a route that will make the request using node but where you then gain the total control over both the response headers and body. You can then add the content header you desire and pass it back to your client.
ref:
https://www.chromium.org/Home/chromium-security/corb-for-developers

"Access-Control-Allow-Origin" Request Error When Accessing API [duplicate]

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 3 years ago.
I'm unable to retrieve data from the Rescue Time API. I'm making a request in a JavaScript file using the jQuery get() method. Here is a look at the JavaScript related to the API GET request:
$.get('https://www.rescuetime.com/anapi/data?key=########################&format=json&restrict_kind=overview', function(data) {
// callback function code...
});
The "key=########################" is the paramater that includes my API key.
When running the script (either locally or on my personal domain), I receive a cross origin error:
XMLHttpRequest cannot load https://www.rescuetime.com/anapi/data?key=########################&format=json&restrict_kind=overview. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I understand that this is happening because i'm requesting content that is on a different domain than the one that is making the AJAX request. That being said, how do I get around this? I've read the CORS MDN documentation, but could not decode what actionable steps I need to follow in order to resolve this issue.
I need some actionable steps.
Set up a CORS proxy using the code from https://github.com/Rob--W/cors-anywhere/ or similar.
https://cors-anywhere.herokuapp.com/ is a public instance running that code, and the way you could use it is by changing your existing code to this:
$.get('https://cors-anywhere.herokuapp.com/https://www.rescuetime.com/anapi/data?key=########################&format=json&restrict_kind=overview', function(data) {
// callback function code...
});
Be aware though that if you do that, your key would potentially be exposed to the operator of that https://cors-anywhere.herokuapp.com/ instance. So if that’s a concern then don’t try it, and instead set up your own proxy at https://some.url.for.your.proxy and change your code to:
$.get('https://some.url.for.your.proxy/https://www.rescuetime.com/anapi/data?key=########################&format=json&restrict_kind=overview', function(data) {
// callback function code...
});
Either way the result will be that your request gets sent through the specified CORS proxy, which forwards the request to the https://www.rescuetime.com/anapi/data… endpoint and then receives the response. The proxy backend then adds the Access-Control-Allow-Origin header to the response and finally passes that back to your requesting frontend code.
Your browser then allows your frontend code to access the response, because that response with the Access-Control-Allow-Origin response header is what the browser sees. Otherwise, if the response lacks Access-Control-Allow-Origin, browsers won’t let your code access it.
A CORS proxy like that is the only option if you want to make the request from frontend JavaScript code running in a browser, and want to consume the response from that frontend code. Otherwise, without the use of such a proxy, browsers will block your code from accessing the response—because the https://www.rescuetime.com/anapi/data… API endpoint doesn’t itself send the necessary Access-Control-Allow-Origin response header.
Your only other option otherwise is to not make the request from your frontend code but instead make the request from whatever backend server-side code you’re running. In that case there’s no browser in the middle enforcing cross-origin restrictions on the request.

REST request from app works, but not from javascript

I'm building an app that has to get and set data at a remote web service through requests. When I use the jQuery GET request it works fine, I can request data from the service without any problems, but when I use PUT I get some erros:
OPTIONS http://myurl.com 501 (Unsupported method
('OPTIONS'))
OPTIONS http://myurl.com Origin null is not allowed by Access-Control-Allow-Origin.
I've tried almost anything to get this to work, but it won't work. I've download a chrome app called REST Console, which can make custom REST requests. The strange thing is that I can interact with my server over that app but not through my javascript!
This is the javascript:
$.ajax({
url: 'http://myurl.com',
type: 'PUT',
data: '<time>16:00</time>',
success: function(data) { alert(data); }
});
Could anybody tell me what is going on here?
First ensure you're serving the page that runs the script from a web server, not directly from the file system.
I'm guessing your service at http://myurl.com is at a different host name to the host name your page is being served from? For it to work in this case you need to implement HTTP headers to support Cross Origin Resource Sharing.
Your service at http://myurl.com needs to handle an HTTP OPTIONS request, the response to which should be a set of HTTP headers (with no content) as follows:
Access-Control-Allow-Origin: http://url-of-page-with-javascript/
Optionally you can also specify Access-Control-Allow-Credentials, Access-Control-Allow-Headers and Access-Control-Allow-Methods. See the full specification here.
You'll also need to add the same headers with the same values when your server responds to the PUT request - obviously the content will also be included with this response.

jQuery, CORS, JSON (without padding) and authentication issues

I have two domains. I'm trying to access a JSON object from one domain through a page on another. I've read everything I could find regarding this issue, and still can't figure this out.
The domain serving the JSON has the following settings:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, OPTIONS"
Header set Access-Control-Allow-Headers "origin, authorization, accept"
From my other domain, I'm calling the following:
$.ajax({
type:'get',
beforeSend: function(xhr) {
var auth = // authentication;
xhr.setRequestHeader("Authorization", "Basic " + auth);
}
url:myUrl,
dataType:'json',
error: function(xhr, textStatus, errorThrown) { console.log(textStatus, errorThrown); }
})
I know that 'auth' is initialized properly (logged and checked). However, this does not work. In Firefox's Console, I get
Request URL: ...
Request Method:
OPTIONS
Status Code:
HTTP/1.1 401 Authorization Required
If I get rid of the beforeSend:... part, I see the following
Request Method:
GET
Status Code:
HTTP/1.1 401 Authorization Required
However, the domain serving JSON also can serve JSONP. I don't want to use this, mainly because the application will be running constantly on a dedicated browser, and I'm worried about this issue. More importantly, I would really like to know what is actually wrong with what I am doing. I know that for practical purposes there are various ways to overcome the JSONP memory leak (such as not using jQuery).
At any rate, when I did use JSONP, my code looked like this:
$.ajax({
url:newUrl,
dataType:'jsonp',
jsonp:'jsonp'
}).done(function(d){console.log(d)})
This gets the following
Request Method:
GET
Status Code:
HTTP/1.1 200 OK
after it prompts me with an alert box for a username and password.
Is there a fundamental difference in the way jQuery handles JSONP requests as opposed to JSON requests? And if so, how can I fix this?
Thanks.
Edit: Here's what I did find.
Basically, because I need authentication, the GET request is sending an Authorization header. However, this is not a "simple" header, and so the browser is sending a pre-flight request (the OPTIONS). This preflight request doesn't have any authentication, though, and so the server was rejecting it. The "solution" was to set the server to let OPTIONS request not require authentication, and report an HTTP status of 200 to it.
Reference: http://www.kinvey.com/blog/item/61-kinvey-adds-cross-origin-resource-sharing-cors
mail-archive[.com]/c-user#axis.apache.org/msg00790.html (not allowed to post more links)
Unfortunately, the "solution" is only working on Firefox and not Chrome. Chrome simply shows the request in red, but doesn't give me any more info on why it failed.
Edit 2: Fixed on Chrome: The server I was trying to get data from had a security certificate which was not trusted. The preflight request on Chrome failed because of this. Solution
superuser[.com]/questions/27268/how-do-i-disable-the-warning-chrome-gives-if-a-security-certificate-is-not-trust (not allowed to post more links)
Welp, now that I have enough rep a while later, I might as well answer this question and accept it.
When you attempt to send a GET json request to a server with headers, the browser first sends an OPTION request to make sure that you can access it. Unfortunately, this OPTION request cannot carry with it any authentication. This means that if you want to send a GET with auth, the server must allow an OPTION without auth. Once I did this, things started working.
Some examples available here may illustrate further how access control can be combined with CORS. Specifically the credentialed GET example. Access control requires that the request set the withCredentials flag to true on the XMLHttpRequest, and for the server handling the OPTIONS method to do two things:
Set Access-Control-Allow-Credentials: true
Not use a wildcard * in the Access-Control-Allow-Origin header. This has to be set to the origin exactly according to the MDN docs on HTTP access control (CORS).
Essentially, the thing processing the OPTIONS request needs to send back appropriate response headers so you can make that credentialed request.
In your question you stated that the service you are interacting with is returning Access-Control-Allow-Origin: *, which is not compatible with a credentialed cross-domain request. This needs to return the origin specifically.
The aforementioned MDN Http Access Control (CORS) documentation also links to the Server-Side Access Control documentation outlining how a server would potentially respond to various cross domain requests - including handling a cross domain credentialed POST request that requires you to send back the correct headers in response to the OPTIONS method. You can find that example here.
Why don't you try typing the URL you are fetching the JSON from into your browser and seeing what happens. It sounds like you literally just need to authenticate into this other website to access it.
If your site needs to work in other browsers like IE, you WILL need JSONP, by the way. The security won't allow the cross site request to work. The headers won't change that. I believe you will also need to add a security policy in your headers.

jQuery cross domain image upload

Ok, so basically.
I inject some javascript code into a web page and it uploads an image on that page to another server.
Now I have it working when I run it on my domain (of course), but I need to post the multipart/form-data request to a PHP file that I do not own.
Since it is a upload and not a simple request to just get data, I cannot use jsonp in the initial call since the response would not be in json.
Using James Padolsey's cross domain script, I am able to do $.get and $.post request across domains, but since I am using $.ajax it does not work.
He uses the Yahoo Query Language to acomplish this
This is basically how I am making the request
$.ajax({
url: 'http://website.com/upload.php',
type: 'POST',
contentType:'multipart/form-data',
data: postData,
success: successCallback,
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('Error');
}
});
I want to make it completely JavaScript based to avoid making my server do the request.
So to re-cap, I can get the image bytes and make the request with javascript. But so far I cannot make it cross domain since I am $.ajax to set the content Type to "multipart/form-data".
Is there another way to make the request cross domain with or without the YQL?
Making the request with an iframe will not work since the domain of the iframe would change and I would not have access to the response.
This is a well known and difficult problem for web development, know as the Same Origin Policy
Javascript prevents access to most methods and properties to pages across different origins. The term "origin" is defined using the domain name, application layer protocol, and (in most browsers) port number of the HTML document running the script. Two resources are considered to be of the same origin if and only if all these values are exactly the same.
There are several ways around this.
Create your own proxy
Create a page that simply forwards the request to the other server, and returns its response
or, Use Apache's rules to form a proxy (see above link)
Use someone else's proxy
For GET requests which are typical Use YQL to access yahoo's proxy
For POST requests, if the 3rd party supports Open Data Tables
or, Use some other public proxy
See if the 3rd party conforms to the CORS specification
Cross domain POST query using Cross-Origin Resource Sharing getting no data back
If you are willing to allow a little flash on your page, try flXHR
it claims to implement the exact XHR api and also has a jquery plugin
These are pretty much your only options

Categories

Resources