XMLHttpRequest status 0 - xmlhttprequest

I'm using jquery ajax call and Chrome javascript console is spitting out an error:
XMLHttpRequest cannot load http://www.1luckypixel.com/eppy/fong_app/index.php/fb_login/login_user. Origin http://1luckypixel.com is not allowed by Access-Control-Allow-Origin.
I've done some searching and find a lot of info for "Origin NULL is not allowed by Access-Control-Allow-Origin." But this is actually giving my domain name as the un allowed origin. I'm not sure what the error means. Also the request goes to the server but doesn't come back and the data in the request isn't past.
Here is my code in case that helps:
$.ajax({
type : 'POST',
url : "<?= base_url(); ?>index.php/fb_login/login_user",
data: {
name:response.name , img:response.link+'/picture' , fb_id:response.id
},
beforeSend : function(thing,data) {
console.log('before', data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('xmlhttprequest', XMLHttpRequest);
console.log('textStatus', textStatus);
console.log('errorthrown', errorThrown);
}
});

www.1luckypixel.com is not the same as 1luckypixel.com
Use a relative URL in your JavaScript, not an absolute one.
Better yet, pick one of the two hostnames to be canonical and redirect all the traffic from the other one to it (with an HTTP 301 status code).

Related

CORS blocking requests in Kotlin lambda but not in identically setup Node lambda

I have a lambda, written in Kotlin with Serverless and CORS just is not working. I feel like I've tried everything. I deployed a Node Lambda with identical sls.sh command and yaml files. The function looks like this
hello:
handler: handler.hello
events:
- http:
path: hello
method: post
cors: true
My responses look like this in both Node and Kotlin:
{
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": "{\"id\": \"f9f76590-xxxx-xxxx-xxxx-9c8e99238f40\"}"
}
In the Node case this all works great. I make a fetch call like this and it works (omitted the Promise resolutions for brevity):
var makeRequest = function (data) {
fetch('https://{lambda URL}/hello', {
'headers': {
'content-type': 'application/json'
},
'body': JSON.stringify({ data }),
'method': 'POST'
})
}
In the Kotlin case I get this CORS error back
Access to fetch at 'https://{lambda URL}/hello' from origin
'http://127.0.0.1:8080' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
I try to "enable CORS" in the API Gateway panel but I get that it's already enabled:
And hit submit I get the error (invalid response status code)
When I hover over the error icon it says "Invalid Response status code specified".
Under Gateway Responses, under every sub item (Default 4XX, Default 5XXX, etc) there are response headers set. This is the same across my Node and Kotlin lambdas.
I'm completely out of ideas at this point.
The only potentially odd thing is I am noticing that in my Node request I see access-control-allow-origin: * in response headers in the browser network panel but in the Kotlin one I don't see it.
From this:
I can see that you haven't created Integration Response in your post method.
Try these configurations:
I discovered my CORS issue was because of server errors. If your server has an error and the API Gateway can't get a response then you get a CORS error because the Gateway itself doesn't have the CORS headers.
While the fix is easy (just handle that server error) it was hard to uncover. I wish this was documented better somewhere so hopefully this is found for others :)
For my case specifically, and why it didn't show up in Node but showed up in Kotlin, was because of types. the browser was sending a type Node automatically corrected the type (number to string) but Kotlin was expecting the type and threw a type error.

Shopify API Cross Domain Ajax Request

I am using the below code to get the customer details from shopify. I have redirected my domain to the other domain from the shopify admin.
function setEmailWithLoggedInUser(callback) {
$.ajax({
url: 'https://new-website-shopify.myshopify.com/admin/customers/'+__st.cid+'.json',
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic XXXXXXXXXXXX")
}, success: function(data){
console.log(data);
if(callback)
callback();
}
})
I have done a lot of work around but unable to find the solution.
I am getting this error:
Failed to load resource: the server responded with a status of 404
(Not Found)
XMLHttpRequest cannot load
https://new-website-shopify.myshopify.com/admin/customers/7094124372.json.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://www.beirutshopping.com' is therefore not
allowed access. The response had HTTP status code 404.
I will save you some headaches with this answer. You cannot call /admin from the front-end of a store, as that exposes your access token to the public. Instead, if you want to access the API from the front-end, use the App Proxy pattern, allowing you to securely make Ajax calls to accomplish your goals.
As it is, you are almost certain to fail, and any success you hack into existence will quickly expose your shop to horrors. Like being replaced with sad pandas, or otherwise being reckd.
var cors = require('cors');
router.use(cors({
origin: '*'
}));
//var config = require('../config/config.json');
//testing /* GET home page. */
router.get('/', function (req, res, next) {
res.setHeader("Content-Type", "application/liquid");
res.setHeader("Access-Control-Allow-Origin", "*");
res.render('index', {
title: 'Store Locator'
});
});

How to get json data from other domain?

I am working in an Angular app. I need to get a Json from the following url:
http://www.citibikenyc.com/stations/json
I tried using $http.get() and $http.jsonp()
When I do the following
$http.get("http://www.citibikenyc.com/stations/json")
.then(function (response) {
console.log(response.data);
});
I am getting the following error :
XMLHttpRequest cannot load [url that i use here].
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' is therefore not allowed access.
When I do the following code:
$http.jsonp("http://www.citibikenyc.com/stations/json?callback=JSON_CALLBACK")
.then(function (response) {
console.log(response.data);
});
I am getting SyntaxError: Unexpected token :
Looks like the service/API you are trying to call doesn't allow you. What you are trying to do is cross-side scripting and is not allowed unless there is a CORS policy on the service that allows your domain. "http://localhost" is not a valid domain for this service.

Crossdomain jQuery ajax request was not called and give error status "parsererror"

I am trying to call cross domain url. which has response text as below.and it is valid json response.
[{"LANG_CODE":"UK_EN","COU_ISO_CODE":"BGR"},
{"LANG_CODE":"UK_EN","COU_ISO_CODE":"HUN"},
{"LANG_CODE":"UK_EN","COU_ISO_CODE":"PRT"},
{"LANG_CODE":"UK_EN","COU_ISO_CODE":"UGA"}]
Jquery ajax code which i am using for calling cross.
$.ajax({
url: "http://someDomainName/restfulservice/Api/Countries/Get_Json",
dataType: 'jsonp',
crossDomain: true,
async: false,
success: function (data) {
alert("success >> "+data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error : "+errorThrown + ", textStatus >> "+textStatus);
}
});
every time it goes to error block. when i inspect this service in browser then it gives response text with valid json string.but through code i am getting error "jQuery18305917718204907095_1409810925309 was not called, status: parsererror".
while this code is working for the url "http://api.geonames.org/findNearbyPlaceNameJSON?lat=47.3&lng=9&username=demo".
what could be the issue for same ?
It is sending back JSON but you have said dataType: 'jsonp'. JSON is not JSONP.
Either change the service to support JSONP or change the client to expect JSON (which might require you to find some other way to circumvent the same origin policy)

jQuery .ajax call returning error when accessing Java Spring service via domain name based URL

My application's HTML5, jQuery Mobile frontend talks to Java server (Spring, Hibernate, MySQL). The application works fine on my notebook as well as in QA environment. On QA, I'm accessing the application using the server's IP address.
When I host the application in Live environment (the same server as QA but a different web app in Tomcat) and try to access it using URL with the domain name, $.ajax calls in the application return error.
One of the calls is as follows:
$.ajax({
type : "GET",
url : "http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi/rest/resource/getResourceTypes",
cache : false,
async : false,
dataType : 'json',
success : function(rTypes) {
Alert("success!");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown);
}
});
I get the following error in Firefox:
An error has occurred making the request: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://www.smartcloudlearning.mobi/js/jquery-1.7.1.min.js :: <TOP_LEVEL> :: line 4" data: no]
I get the following error in Chrome:
An error has occurred making the request: Error: NETWORK_ERR: XMLHttpRequest: Exception 101
In the server log, I see that the requested Spring service was successfully invoked but it looks like the client doesn't receive the data!
If I hit the URL
http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi/rest/resource/getResourceTypes
directly in the browser, I get expected results! I sense that this is somehow due to how I forward server request from Apache to Tomcat.
The following are the lines in Apache / httpd server's httpd.conf file:
ProxyPass /SmartCloudLearningMobi http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi
ProxyPassReverse /SmartCloudLearningMobi http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi
Can anyone tell me what's amiss here? Much appreciated!
I managed to solve the problem:
The browser was giving the error on .ajax call because I had port number in my URL. The port number got carried over when I created 'live' URL from my QA URL. When I removed the port number from the .ajax call's URL, the call started returning success!
Jason Foglia, your statement "... and also the port..." nudged me to explore that angle... thanks a lot!
You're probably getting an error because of a security concept called "same origin policy" which doesn't allow you to call a service from a different domain. Or at least, disallow you from calling a method in that service.
Same discussion is found here - AJAX Cross Domain
You can however implement a cross-domain using JSONP - Wikipedia on JSONP
The solution is to change the datatype to JSONP:
$.ajax({
url:"http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi...",
dataType: 'jsonp',
...
});
Try using an relative url:
If that doesn't work is the domain name the same as the url and also the port.
Browsers don't allow cross domains.
$.ajax({
type : "GET",
url : "/SmartCloudLearningMobi/rest/resource/getResourceTypes",
cache : false,
async : false,
contentType : "application/json"
dataType : 'json',
success : function(rTypes) {
Alert("success!);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown);
}
});
The browser was giving the error on .ajax call because I had port number in my URL. The port number got carried over when I created 'live' URL from my QA URL. When I removed the port number from the .ajax call's URL, the call started returning success!
Jason Foglia, your statement "... and also the port..." nudged me to explore that angle... thanks a lot!