post a json to a restful web service from html file - ajax

I am trying to post a json to a restful web service from html file and it is showing
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource"
Code Sniplet from html ajax function:
var serviceurl="http://192.168.0.100:8080/login";
var data = {'emailId':'foo','password':'dog'};
$.ajax({
url: serviceurl,
type: 'GET',
contentType:'application/json',
data: JSON.stringify(data),
dataType:'json',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function(data){
//On ajax success do this
alert(data);
}});

Do you know the The Same Origin Policy? https://en.wikipedia.org/wiki/Same-origin_policy.
Should you call serviceurl from your server and redirect the response to the client? Should you use a iframe for do the ajax call? should you use a browser started without the S.O.P.( for chrome :"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --args --disable-web-security)?
Please give more information and where you can put your hands :-)

Related

Avoid CORS in rest API

I'm having a problem to make a call to a rest API.
In the document (FAQ) of the web application there is an example that use AJAX request to make the call. Here an example:
var url = 'https://example.com/yyy';
$.ajax({
type: 'POST',
url: url,
cache: false,
data: {
opt: JSON.stringify(example)
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result)
{
console.log(result);
} });
I created a local page with this code to made the post to the API that is located on a remote server but I receive an error about CORS.
Is there any solution to circumvent this problem? I tried to use firefox plugin to allow CORS but it didn't solve the problem. The session is authenticated via form before use the endpoint.
I see several issues:
Try to run the code from a domain and not from local disk (alternatively you can consider using https://crossorigin.me/ )
How does the authentication work? if with cookies you need to add withCredentials to the ajax request.
Make sure the API returns Access-Control-Allow-Origin: foo header where foo is the domain your code runs in. If you also used withCredentials, you should add Access-Control-Allow-Credentials: true

Server says the request went through but client says error

I am building a web app and for the server I am using nodejs and express. When I make a request to the server just from the browser it works fine, but when I try an ajax request from the client it registers on the server, but gives me an error on the client. Here is what I am using for the ajax request:
$.ajax({
async: false,
dataType: "json",
url: url,
crossDomain: true,
success: function(response) {},
error: function(response){
alert(JSON.stringify(response));
}
});
on server side, when you send the request... set header of response to allow cors:
something like this >>
res.writeHead(200,{
'Access-Control-Allow-Origin' : '*'
});
In place of '*', you can specify a set of urls, you want to server response to...

Logging into an expressjs app with CORS

I have expressjs sitting on a nodejs server and I have a client side cordova app making ajax requests to certain routes.
This is fine until I need to make a POST request to login using passportjs, there is a 302 redirect that takes place so I get this 302 Moved Temporarily when making this call
$('body').on('submit', '#logIn', function(e){
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: "http://mydomain.io:3300/login",
data: JSON.stringify(formData),
type: "POST",
crossDomain: true,
dataType: "json",
async: true,
success: function(response){
alert('succeeded!');
console.log(response);
alert(response);
},
failure: function(message){
alert("failed");
console.log(message);
alert(message);
}
});
});
So my question is how is it possible using CORS to login to the app using client side ajax?
CORS is not your problem here.
Passport wants to redirect your user (based on the values you've passed to passport.authenticate). For instance:
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { successRedirect: '/',
failureRedirect: '/login' }));
Passport will tell the browser to redirect to / or /login by returning a 302. You can remove the redirect by removing the second parameter to passport.authenticate:
app.get('/auth/facebook/callback',
passport.authenticate('facebook'));
This will call next() on successful authentication (and return 401 otherwise).
The examples here use FacebookStrategy, but it works with any strategy.

CORS Logging into an expressjs/passportjs app 401 Unauthorized

I am converting a web app into a cordova app the only thing stopping me is the fact that the app is expressjs based, since cordova requires an index.html I need to use CORS to render the app and provide the login session.
I can use ajax/CORS with regular pages but when it comes to authorization I am stuck.
I use passportjs to authenticate on this POST route app.post('/login', passport.authenticate('local-login')); so on my client side cordova app I make an ajax call to make this request for me.
$('body').on('submit', '#logIn', function(e){
e.preventDefault();
var formData = $(this).serialize();
console.log(formData);
$.ajax({
url: "http://mysite.io:3300/login",
data: JSON.stringify(formData),
type: "POST",
crossDomain: true,
dataType: "json",
async: true,
success: function(response){
alert('succeeded!');
console.log(response);
alert(response);
},
failure: function(message){
alert("failed");
console.log(message);
alert(message);
}
});
});
When I make the POST request I get a 401 Unauthorized so I have been doing research on that, I still am not sure why it's not authorizing?
From the Passport docs:
By default, if authentication fails, Passport will respond with a 401 Unauthorized status, and any additional route handlers will not be invoked.
The username/password combination you're posting is not valid.

Basic Authentication and jQuery/ajax call

I would like to call OData .NET web service that authenticates users via basic authentication.
I use following ajax call:
var fullUri = APIUri + "?$format=json";
$.ajax({
url: fullUri,
contentType: "application/json",
dataType: "jsonp",
type: 'GET',
jsonp: '$callback',
beforeSend: function setHeader(xhr) {
xhr.setRequestHeader('Authorization', token);
},
success: callback,
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
},
});
The results are unusable for me:
Calls are blocked because of CORS (until I will paste API url and try to load it in chrome). I tried local html file and html file uploaded to the same domain/port, but authentication fails (according to Chrome console).
Once I enter service URL into chrome address bar, I am asked to provide login name and password by Chrome. If I enter them, they are cached and used even I assign them in beforeSend. How to blocks this behavior?
I've tried a lot of examples how to configure jsonp, headers etc, but did not find working solution yet.
IIS server response header is also configured using "Access-Control-Allow-Origin" value="*".
You can set the HTTP Password and Username in the AJAX Call directly:
$.ajax({
url: fullUri,
contentType: "application/json",
username: <login>,
password: <password>,
...
Use the following to support CORS:
jQuery.support.cors = true;
Regarding the call, are you using HTTPS? Is the certificate valid?

Resources