salvatore salvatore - 7 months ago 74
Javascript Question

403 Forbidden Response to a JSONP request

First time posting to stackoverflow.

I'm just trying to get the data from a json url using jquery.
First problem was the cross origin request block, even with libraries that are supposed to stop this issue, like ajax cross origin js (sorry not to provide this link, I'm too new to have more than 2 links on here), I was still having no luck, same cross origin error.

so I moved to JSONP.

url = "http://take-home-test.herokuapp.com/api/v1/works.json?callback=?"
$.ajaxSetup({ dataType: "jsonp" });
$.getJSON(url, function(json) {
console.log(data);
});


(the AJAX syntax for a JSONP request I tried too)

Now I can see in the network tab that the data is returning back but the status is 403 forbidden.
pic of the response in the network tab of chrome

I'm using http-server that you can install with npm to avoid chrome having issues with the json MIME type.
This similar stack overflow answer says I needed to integrate jsonp support for my framework but they were referring to sinatra for ruby.
Why Does JSONP Call Return Forbidden 403 Yet URL can be accessed in a browser

So I tried out npmjs jsonpclient and still got the forbidden response.

Any ideas? This has taken me over a day.

Answer

The problem: The server (http://take-home-test.herokuapp.com) does not have 'Access-Control-Allow-Origin' headers set. If you have access to the server, start it with the '--cors' option. Aka: node bin/http-server --cors ... This will enable CORS via the Access-Control-Allow-Origin header and should resolve your problem.

If you do not have access to the server. Here's a quick solution: proxy your request through http://cors.io. See below.

url = 'http://take-home-test.herokuapp.com/api/v1/works.json?callback=?';
new_url = "http://cors.io/?u=" + encodeURIComponent( url );

$.ajaxSetup({ dataType: "jsonp" });
$.getJSON(new_url, function(json) {
    console.log(json);
});

JSFiddle: http://jsfiddle.net/davemeas/4rt3s7ta/1/ (note: you have to add jQuery to that fiddle :) )

Comments