Request Forbidden 403 when request made to Square-Connect from localhost - angularjs

I am trying to make a request to 'https://connect.squareup.com/v2/locations' using angularjs, where call is getting failed saying 403 FORBIDDEN.
Here is the code sample :
var url = 'https://connect.squareup.com/v2/locations';
var config = {
headers: {
'Authorization': 'Bearer sandbox-sq0atb-JJGltCa375qzAyoQbjPgmg',
'Accept': 'application/json',
"X-Testing": "testing"
}
};
$http.get(url, config)
.then(
function (response) {
console.dir(response);
},
function (response) {
console.log("failed" + response)
}
);
I have made a fiddle of the above sample. Any help is appreciated.
http://jsfiddle.net/dx6tdrha/

Are you seeing this error: XMLHttpRequest cannot load https://connect.squareup.com/v2/locations. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.? It means that you cannot access the API via front-end Javascript (like AngularJS) You'll need to use a different implementation like Node.js, PHP, etc.

Related

How do i enable cors policy / or request in react js with no access to the API?

Im using RapidApi to make som simple calls for fetching country data using axios. The API is paged in that the next response will have the URL for the next request. So basically i don't even have the URLs.
Problem i get the error which i have seen all over stack overflow about cors policy
Access to XMLHttpRequest at 'https://api.hybridgfx.com/api/list-countries-states-cities?page=2' from origin 'http://localhost:3002' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I tried adding the line "access-control-allow-origin": "*" but that doesn't work and i still get the same error. When i click on the URL or just run it directly on the browser i get a bunch of data but when it is called in the code it blows up . Please help.
const fetchNextResults = async (url: string): Promise<FetchResponse> => {
const options = {
method: "GET",
url: url,
headers: {
"X-RapidAPI-Key": MyKey,
"X-RapidAPI-Host": "countries-states-cities-dataset.p.rapidapi.com",
"access-control-allow-origin": "*",
},
};
const res: FetchResponse = await axios
.request(options)
.then(function (response) {
console.log(response.data);
return response.data;
})
.catch(function (error) {
console.error(error);
});
return res;
};
You can send a request throw the CORS proxy.
List of proxies.
url: <proxy url>/<my url>
Or create your own.

405 method not allowed using $http service AngularJS

I'm getting a 405 error making a request from localhost, this is the full error:
OPTIONS http://www.myurl.com 405 (Method Not Allowed)
XMLHttpRequest cannot load http://www.myurl.com. Response for preflight has invalid HTTP status code 405
I understand the problem but the quirk is that I get this error just when I use the angular $http service:
var req = {
method: 'POST',
url: 'http://www.myurl.com',
headers: {
'Content-Type': 'application/json'
},
data: {
}
}
$http(req)
.then(function(res) {},
function(error) {});
Using XMLHttpRequest works perfectly:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText);
}
};
xhttp.open("POST", 'http://www.myurl.com', true);
xhttp.send();
I have a chrome extension to add CORS headers and it is working. I also notice that if I remove the third parameter in xhttp.open the error appears again.
¿Does anyone know the reason? ¿How can I use the angular services without get the error?
You can write like this. Because you are not sending any parameter to the url. So I think this is a good way to do this. just try it may work for you.
$http.post('http://www.myurl.com').
success(function(data) {
//success Response here
});
You need to allow OPTIONS method on your server side. Before every GET, POST, PUT, DELETE... requests an OPTIONS request is launched.
I advise you to disable your "chrome extension to add CORS", to have the same configuration of your final users.

CORS Issue in Web Console (angular js)

I have a developed a web console in angular JS in which I am using post and put methods and making HTTP requests in which I send json and calling a WSO2 REST API to get response accordingly. Its running on server but I am facing CORS problem. I have add add extension in browser and enable it otherwise I get following error.
XMLHttpRequest cannot load http://127.197.200.100:8000/ManagementAPI/createuser. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.197.200.100:8000' is therefore not allowed access.
This is how I am sending request
CreateUser: function(adata) {
var config = {
headers :{
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
var promise = $http.post(213.187.243.177:8283/ManagementAPI/createuser,adata,config).then(function (response) {
return [response.status,response.data];
},function (response) {
console.log("Error Returned" + response.status);
return [response.status,response.data];
});
return promise;
},
I have tried ThisLink for solution but did not work. Need a solution for accessing it without CORS.
Set headers in back end for avoiding CORS issues .
Sample code in php is shown in below
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}

I can't upload my files using angularjs?

$scope.uploadFiles = function () {
//debugger;
var request = {
method: 'POST',
url: 'http://localhost/upload/',
data: formdata,
headers: {
'Content-Type': undefined
}
};
// SEND THE FILES.
$http(request)
.success(function (d) {
alert(d);
})
.error(function () {
});
}
i am getting in console window like
XMLHttpRequest cannot load http://localhost/upload/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:55555' is therefore not allowed access. The response had HTTP status code 405.
If I understand this correctly, the app is running at http://localhost:55555 and you are trying to send a POST request to http://localhost/upload/ (which really means http://localhost:80/upload/). Your browser is not allowing you to do this since http://localhost:80/ and http://localhost:55555/ are different origins.
Perhaps you meant to say http://localhost:55555/upload/? This would solve your issue.
Otherwise you need to disable CORS in your browser or add the 'Access-Control-Allow-Origin: * header in your server at http://localhost:80/.

AngularJS POST fails with No 'Access-Control-Allow-Origin' when using data payload object but works using query params like payload

I am facing a weird issue. I am running my angularjs app in nodejs server locally which calls a POST API from my app located on Google App Engine. The API is configured with all CORS headers required as follows:
def post(self):
self.response.headers.add_header("Access-Control-Allow-Origin", "*")
self.response.headers.add_header("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS")
self.response.headers.add_header("Access-Control-Allow-Headers", "X-Requested-With, content-type, accept, myapp-domain")
self.response.headers["Content-Type"] = “application/json; charset=utf-8”
GET requests to the API work without issues.
POST requests to the API work but ONLY when I send the post data as a 'string of params' and NOT when post data is sent as an object which is the right way to do. Eventually I need to be able to upload pictures using this API so the first solution below might not work for me. Please help!
METHOD 1: This works:
postMessageAPI = "https://myapp-qa.appspot.com/message";
var postData = "conversationid=1c34b4f2&userid=67e80bf6&content='Hello champs! - Web App'";
var postConfig = {
headers: {
"MYAPP-DOMAIN" : "myapp.bz",
'Content-Type': 'application/json; charset=UTF-8'
}
};
$http.post(postMessageAPI, postData, postConfig).
success(function(data){
$log.log("POST Message API success");
}).
error(function(data, status) {
$log.error("POST Message API FAILED. Status: "+status);
$log.error(JSON.stringify(postData));
});
METHOD 2: This fails:
postMessageAPI = "https://myapp-qa.appspot.com/message";
var postData = ({
'conversationid' : '1c34b4f2',
'userid' : '67e80bf6',
'content' : 'Hello champs! - Web App'
});
var postConfig = {
headers: {
"MYAPP-DOMAIN" : "myapp.bz"
'Content-Type': 'application/json; charset=UTF-8'
}
};
$http.post(postMessageAPI, postData, postConfig).
success(function(data){
$log.log("POST Message API success");
}).
error(function(data, status) {
$log.error("POST Message API FAILED. Status: "+status);
$log.error(JSON.stringify(postData));
});
When I use METHOD 2 it fails with the following error in the console:
XMLHttpRequest cannot load https://myapp-qa.appspot.com/message.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://0.0.0.0:8000' is therefore not allowed access.
Please let me know if you have any solution. Thanks in advance.
The issue is most likely with Angular sending a pre-flight OPTIONS request to check the access headers from the server. I am not sure how OPTIONS requests are handled in your API, but I am betting these headers are not being added. I suggest installing Fiddler to monitor the actual requests to see what is going on with the headers. You may only be adding them to your POST responses.
See this answer for details on why METHOD 1 may work in this scenario, while METHOD 2 does not.
Here are some more details about pre-flight requests.

Resources