getJson Access-Control-Allow-Origin - json

I just learned that using getJson with a url from another domain/port will usually lead to cross domain policy problem.
With this code:
var appGetApi = "http://localhost:30028/api/values";
$.getJSON(appGetApi, function (_returnedJson) {
...
});
I get this error:
XMLHttpRequest cannot load http://localhost:30028/api/values.
Origin http://localhost:17437 is not allowed by Access-Control-Allow-Origin.
After searching the web for answers, it seems that adding &callback=? is a famous fix. So i did that.
var appGetApi = "http://localhost:30028/api/values&callback=?";
$.getJSON(appGetApi, function (_returnedJson) {
...
});
But I still get an error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
http://localhost:30028/api/values&callback=jQuery11020629610788077116_1373178114158?_=1373178114159
This is my first time with API and I am completely clueless right now on how to solve this issue. Please help me guys. Thanks.

By default, IIS in W2K3 and above won't serve files that aren't of a MIME type that it knows about (instead returning 404 errors).
You need to add a MIME type to IIS to allow it to serve that type of file. You can set it at the site level or at the server level.
To set this for the entire server:
Open the properties for the server in IIS Manager and click MIME Types
Click "New". Enter "JSON" for the extension and "application/json" for the MIME type.

Related

How to detect SSL errors using chrome extension? [duplicate]

I'm doing simple GET request to my URL and I get the error "ERR_INSECURE_RESPONSE". THis is fine, as certificate is self-signed. But I have two questions regarding it:
Is there a way to overcome this in extension? Like setting a flag in request or sth like that? (probably not likely)
Is there a way just to handle this error (to notify user)? I've checked all XMLHttpRequest fields and cannot see anything that can indicate this error. Status field has value of 0 (zero).
Any ideas?
No, the extension API does not offer any method to modify SSL settings or behavior.
You could use the chrome.webRequest.onErrorOccurred event to get notified of network errors. The error property will contain the network error code.
For example:
chrome.webRequest.onErrorOccurred.addListener(function(details) {
if (details.error == 'net::ERR_INSECURE_RESPONSE') {
console.log('Insecure request detected', details);
}
}, {
urls: ['*://*/*'],
types: ['xmlhttprequest']
});
var x = new XMLHttpRequest;
x.open('get','https://example.com');
x.send();
If for testing only, just start Chrome with the --ignore-certificate-errors flag to allow self-signed certificates to be used. This affects all websites in the same browsing session, so I suggest to use a separate profile directory for this purpose, by appending --user-data-dir=/tmp/temporaryprofiledirectory to the command line arguments.
Another way to avoid the error in the first place is to get a valid SSL certificate. For non-commericial purposes, you can get a free SSL certificate at https://www.startssl.com.

How get data from rest api URL in angularJs? While i'm try to get its show me as 0kb file

function Hello($scope, $http) {
$http.get('http://localhost/api/Country')
.success(function(data, status) {
$scope.greeting = data;
}).error(function(data, status){
alert('Error');
});
}
URL: Try pull the data from url, it shown me as a 0kb file. when i click that URL directly in shown some data.
Tried on my application before you replace the url by localhost (I guess changed for security reason), seems to come from a wrong configuration on server side, not angular.
Firefox trigger an error saying :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/api/Country. This can be fixed by moving the resource to the same domain or enabling CORS.
If you are in charge of this server, you should give a look at Cross-Origin Request, but your angular code is correct, sorry :D

How to handle ERR_INSECURE_RESPONSE in Google Chrome extension

I'm doing simple GET request to my URL and I get the error "ERR_INSECURE_RESPONSE". THis is fine, as certificate is self-signed. But I have two questions regarding it:
Is there a way to overcome this in extension? Like setting a flag in request or sth like that? (probably not likely)
Is there a way just to handle this error (to notify user)? I've checked all XMLHttpRequest fields and cannot see anything that can indicate this error. Status field has value of 0 (zero).
Any ideas?
No, the extension API does not offer any method to modify SSL settings or behavior.
You could use the chrome.webRequest.onErrorOccurred event to get notified of network errors. The error property will contain the network error code.
For example:
chrome.webRequest.onErrorOccurred.addListener(function(details) {
if (details.error == 'net::ERR_INSECURE_RESPONSE') {
console.log('Insecure request detected', details);
}
}, {
urls: ['*://*/*'],
types: ['xmlhttprequest']
});
var x = new XMLHttpRequest;
x.open('get','https://example.com');
x.send();
If for testing only, just start Chrome with the --ignore-certificate-errors flag to allow self-signed certificates to be used. This affects all websites in the same browsing session, so I suggest to use a separate profile directory for this purpose, by appending --user-data-dir=/tmp/temporaryprofiledirectory to the command line arguments.
Another way to avoid the error in the first place is to get a valid SSL certificate. For non-commericial purposes, you can get a free SSL certificate at https://www.startssl.com.

Cannot run xmlhttprequest in Chrome App : provisional headers & No 'Access-Control-Allow-Origin'

I am building a chrome app sending a Get HTTPRequest to an external API:
I get the answer:
XMLHttpRequest cannot load
http://developer.echonest.com/api/v4/artist/profile?api_key=FILDTEOIK2HBORODV&name=weezer.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'chrome-extension://ihdfphmemcdeadpnjkhpihmcoeiklphe'
is therefore not allowed access.
I did allow the external domain in permissions in my manifest (to prevent blocking in cross domain requests)
When I type the URL in the Address Bar it works perfectly
It seems Chrome is blocking my request, I even tried to load directly the script in an HTML page and it does not work (same message but with origin "null") (oh and it did not allow me to cheat by changing the Origin in the Header).
I also get the famous "Caution : Provisional Headers are shown" in the console, which makes me think Chrome is blocking my request, I looked up on other Stack Overflow Questions but apart running chrome://net-internals and looking for stuff I haven't the first clue about I cannot find any good answers (I did run chrome://net-internals but really can't make any sense out of it).
Here is the request :
function update_stations() {
var xhr = new XMLHttpRequest();
xhr.open("Get","http://developer.echonest.com/api/v4/artist/profile?api_key=FILDTEOIK2HBORODV&name=weezer", true);
xhr.responseType = "json";
xhr.onreadystatechange = function() {
console.log("Essai");
console.log(xhr.readyState);
console.log(xhr);
document.getElementById("resp").innerText = xhr;
}
xhr.send()
}
Any thoughts (would be highly appreciated)?
Cross-Origin XMLHttpRequest chrome developer documentation explains that the host must be listed in the permissions of the manifest file.
I've taken the XHR code from above and included it in the hello world sample. It works after adding the following to the manifest.json.
"permissions": [
"http://*.echonest.com/"
]

Custom 404 error without server

Is possible to intercept 404 error without using web server (browsing html file in the filesystem) ?
I tried with some javascript, using an hidden iframe that preload the destination page and check for the result and then trigger a custom error or redirect to the correct page.
This work fine but is not good on perfomance.
A 404 error is an HTTP status response. So unless you are trying to retrieve this file using an HTTP request/response, you can't have a genuine 404 error. You can only mimic one in something like the way you suggest. Any "standard" way of handling a 404 error is dependent on your flavour of web server anyway...
404 is a HTTP response code, and as such only delivered through the HTTP protocol by servers that speak it. The file:// extension isn't a real protocol response as such, it's a hack built into clients (like browsers) that enable local file support, however it's up to browsers / clients themselves whether they expose any response codes from their file:// implementation. In theory they could report them in the DOM, for example, but they would be response codes exposed to themselves, and as such rarely implemented. Most don't, and there isn't a standard way for it. You may look into browser extensions, like Firefox, and see if they support it, but then, this is highly unstandard and will likely break if you pop it on the web.
Why don't you want to use the server?
I don't believe that it's possible to handle a 404 error client-side, because a 404 error is server-side.
Whenever you load a webpage, you make a request to the server. Thus, when you ask for a file that's not there, it's the server that handles the error. Regular HTML/CSS/JavaScript only come into the picture when the server sends back a response to tell you that it can't find the file.
Steve
Because I was looking for this today. You can now do this without a server by using a Service Worker to cache the custom 404 page, and then serve it when a fetch request status is 404. Following the instructions on the google cache lab, the worker files looks as follows:
const filesToCache = [
'/',
'404.html'
];
const staticCacheName = 'pages-cache-v1';
self.addEventListener('install', event => {
console.log('Attempting to install service worker and cache static assets');
event.waitUntil(
caches.open(staticCacheName).then(cache => {
return cache.addAll(filesToCache);
});
);
});
self.addEventListener('fetch', event => {
console.log('Fetch event for ', event.request.url);
event.respondWith(
caches.match(event.request).then(response => {
if (response) {
console.log('Found ', event.request.url, ' in cache');
return response;
}
console.log('Network request for ', event.request.url);
return fetch(event.request).then(response => {
console.log('response.status:', response.status);
// fetch request returned 404, serve custom 404 page
if (response.status === 404) {
return caches.match('404.html');
}
});
});
);
});