Server says the request went through but client says error - ajax

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...

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

How to use ajax in reactjs on localhost

Below is my code:
While using local url I am getting the error
"Failed to load http://localhost/reactjs/my-app/lib/ajax.php: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access"
But when I used live url such as "https://jsonplaceholder.typicode.com/todos" its working fine.
$.ajax({
url: 'http://localhost/reactjs/lib/ajax.php',
//url: 'https://jsonplaceholder.typicode.com/todos',
type: 'GET',
dataType: 'jsonp',
//contentType: "application/json; charset=utf-8",
//jsonp: "json_callback",
crossOrigin: true,
//cors: true,
//data: {user_name:username, user_type: usertype, password: password,mode: 'Login' },
success: function(data){
alert(data);
},
error: function(error){
console.log(error);
}
});
You are calling different host so that's why you have CORS issue. Your application is running on localhost:3000 and you are calling your service on localhost.
You can do what Vivek suggests (if it is different host) or you just need to have proper port referenced (if both applications are on localhost:3000).
Note that you don't have to write absolute url in ajax. Instead, if it is on same host, you could just write /reactjs/lib/ajax.php.
Add this on php side :
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
And this url http://localhost/reactjs/my-app/lib/ajax.php should be http://localhost/reactjs/lib/ajax.php

post a json to a restful web service from html file

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 :-)

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.

cross domain request with ajax

I am trying to redirect from my local domain to Paypal checkout domain using ajax request.I am also allowing cross domain to true.but I am getting the error that
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
my code is :
$.ajax({
type: 'GET',
url: url,
processData: false,
crossDomain: true,
contentType: "application/json",
jsonp: false,
success: function() {
alert("Success");
},
error: function() {
alert("failure");
}
});
In order for a CORS request to be allowed, the SERVER side needs to populate the Access-Control-Allow-Origin Header in the response. I would presume that the Paypal servers do not do this and so this is why you are receiving the error.
For more information, see this link: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

Resources