Javascript post requests cross domain with cookies - javascript

Using Javascript I want to make multiple POST requests cross domain. In the first instance, I store the response cookies in a variable, then I resend for a second POST request..
For example, in ruby i'd do something like this:
#http = Net::HTTP.new("myhost.com", 80)
// first request
data = "param1=xxxx&param2=yyyy&param3=zzzz"
resp = #http.post("/firstrequestform", data, {'User-Agent'=>'me'})
// second request
#cookie = resp['set-cookie']
headers = { "Cookie" => #cookie, "Referer" => "http://myhost.com/firstrequestform" }
data = "param1=xxxx&param2=yyyy&param3=zzzz"
resp = #http.post("/secondrequestform", data, headers)
Is it possible to do this in Javascript given cross domain restrictions. Maybe possible using an iframe, but how would you control the cookies? I'd also like to set custom headers within the iFrame, such as the Referer header.
If it's not possible, does anyone know of a browser plugin that can be used to do this?
Thanks.
UPDATE
Unfortunately in this case its not possible to route any request through a 3rd party server (all the code has to be on the client side).

Simplest would be use your server as a proxy. Make an AJAX request to your server, and use your Ruby code shown to make request to other domain and output the response to AJAX request

Related

CORS policy: No 'Access-Control-Allow-Origin' / 500 (Internal Server Error) Problem

Basically, I'm trying to get a username by id from Sequelize. The problem is that I am either stuck with a CORS problem or 500 Internal Server error depending on the response(status)
cors and 500
controller code
async getUserFromUserId (req, res) {
try {
// const user = await User.findByPk(req.body.id)
const id = req.body.id
const user = await User.findByPk(id)
res.send(user.username)
} catch (err) {
// or res.status(some random number).send() for CORS problem to appear
res.status(500).send({
error: 'an error has occured trying to fetch the users id'
})
}
},
client code
this.notifiedUser = (await UserService.getUserFromUserId({id: UserId})).data
I get a Status: 200 OK from postman though.
Postman Solution
Edit:
I have seen how the other Solution for the cors thingy, but the solutions does not specify as to why I get "undefined" results after resolving the cors problem.
So, CORS is actually really obnoxious in this regard, but there's a fairly straightforward way to fix this. It's a super useful security feature, though it is frustrating at best sometimes.
Your browser does what is called a Preflight Request, which is of the http verb OPTIONS. Your browser calls whatever route you want, but instead of what you asked it to do, it calls using OPTIONS first. Your server should accept all routes that the client can ask for with the OPTIONS method, and your server should respond with the following headers to be an externally available, cross-origin API.
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, ...
(note, you should not put the ... in, but you can put any HTTP verb in this list)
If you require your own headers (for auth purposes), you want to add this header for Client -> Server.
Access-Control-Allow-Headers: YourHeader, YourHeader2, YourHeader3
You want to add this one for Server -> Client
Access-Control-Expose-Headers: YourHeader,YourHeader3
Note that the OPTIONS call is an entirely separate call that you should handle as well as the GET method.
You've now told the browser what it is allowed to ask for, and what it can expect to get back from your API. If you don't respond to the OPTIONS request, the browser terminates the request, resulting in a CORS error.
I'm going to take a gander at a guess and assume you're likely using Express, which this answer describes how to set the headers on.
What do the headers mean, in English?
Access-Control-Allow-Origin
From where are clients allowed to access this resource (endpoint)? This can match partial domains with wildcards, or just a * to allow anywhere.
Access-Control-Allow-Methods
What HTTP methods are permissible on this route?
Access-Control-Expose-Headers
When I get a response from the server, what should I (the browser) expose to the client-side?
Access-Control-Allow-Headers
What am I as the client side allowed to send as headers?
Okay, so I figured out the problem.
In a way, I did not have to deal with any of the cors stuff because I believe that was not the main source of the problem.
So, instead of accessing my database data through "GET" and getting the data by doing this:
this.data = (Service.function(bodyValue)).data
I did "POST" to get the data, and accessed the data by simply doing this
const response = Service.function({
id: bodyValue
})
this.data = response.data
This accesses the data without having to get "secured" information from the database, but by accessing the data from the database by getting Observer object info from the database.
The Observer object looks as follows, which treats the user data as an object instead of pure data.
Compared to a data object, where each data {...} has user information.
I am not sure if I am using the correct words, but these are to the extent of my current understanding.
If your origin is from localhost, Chrome usually blocks any CORS request originating from this origin.
You can install this extension:
https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en
Or you can disable the security when running chrome (add the flag):
--disable-web-security

Unable to call web-service from angularjs app

Unable to call post webservice from my application. following is the code.
var postLogin = "http://0.0.0.0:000/ddd/v1/login";
var loginvalue = {"email":"some#mail.com","password":"cbsjc6dw3bgjyfdgdKHGGDF="};
var config = {
headers: {
'Content-Type': 'application/json'
}
}
$http.post(postLogin ,loginvalue,config ).success( function(response) {
alert("response "+ response)
$scope.defer.resolve(response);
}).error(function(error){
alert("dddddd" + JSON.stringify(error));
})
If i write this code then it is returning as 400 error but if i use the postman application of google then i am getting the response without any error. So i am in confusion that whatever the code i have written is right or wrong. Hence i need to solve this issue.
Please go through the above image.
This usually happens when Client and Server are on different domains. The POST requests done by the client are first verified with a OPTIONS pre-flight check, to see if a POST would be possible. Sometimes, servers are configured to not allow OPTIONS request method. This will be the outcome of a pre-flight OPTIONS check, in such a case.
There is more information here - Why is an OPTIONS request sent and can I disable it?
Other resources for understanding the concept and helping us to configure the Response headers from the Server-side application are here:
https://medium.com/#praveen.beatle/avoiding-pre-flight-options-calls-on-cors-requests-baba9692c21a
https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
At the end of the day, if the Server is NOT configured to handle Cross-site requests, nothing can be done from the client-side.
Also, there are cases where the server does allow cross-site request, processes and send the response back to client, without the Access-Control-Allow-Origin header or with the Access-Control-Allow-Origin header, but not the same as the request origin or a wildcard "*". In such cases, browser stops processing the response, even when the call turns out to be in HTTP 200 OK Status.
Below is one such example, that I recently encountered while integrating with an external application.

How to make a cross domain request from javascript

var http = new XMLHttpRequest();
var url = "http://example.com/";
http.crossDomain = true;
http.withCredentials = true;
http.open("GET", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send();
console.log(http.responseText);
When i try to do a cross domain request from the javascript as seen in the code, it throws me an error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. How can i resolve that since i don't to persue solution of JSONP. Are there any other solutions from which i can resolve it. And i don't have control on the server side since its a third party server.
There is no way to read the data using purely client side code.
You need to make the request from a server, and have the client side code fetch the data from that server.
Said server will either be the same origin as the page hosting the JS or it will be one that uses CORS to grant permission to your origin.
The problem is that this request is thrown by the client rather than the server.
One way to solve this is to use a proxy, e.g. a PHP proxy, so that you actually retrieve the data via a server script (for instance using cURL) and make your JS script request your server page instead of the cross-server one.
PHP web proxies already exist, and looking here or here might give you an idea on how to achieve what you're looking for.
There is no way to make it using JS only, apart from asking the other server's owner to whitelist you, which in most cases is really unlikely.

Null response using $.getJson() function

I have been trying to get a response from a server sending a GET URL, but isn't working for this particular server, on the other hand, when I put the same GET URL in the browser I obtain an answer. The server is in django python and I don't have access, because I'm currently programming the client side.
This is the javascript code:
var url = "https://www.mysite.com/module/get_requ/?user=ms&money_type=F&coin-count=1&pass=test&slots_id=12&line-value=9&slots_type=12&cacheBuster=1278933269465&coin-value=0.05";
$.getJSON(url,
function(data){
alert(data);
});
but when i do:
var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=jso&jsoncallback=?";
In the above code it work perfect. So, I want to know if i'm doing something wrong, or the problem is in the server side.
This is most likely because of same origin policy. The flicker api uses JSONP, which is not subject to the SOP. So, unless bingocastle.co.uk also exposes a JSONP interface, you will not be able to request data from bingocastle.co.uk client side, without going through some server proxy.

Difference between localhost and IP address in Ajax request sending

I have a strange problem with native Ajax request invoking.
I am creating the Ajax object and sending the request like follows:
var xmlHttpObj = new XMLHttpRequest();
....
xmlHttpObj.open("GET","http://192.168.16.254:8080/ajax/demoExample.html",true);
xmlHttpObj.send();
When I access the servlet with the URL something like http://localhost:8080/ajax...,
then I am not able to get the response in the client side. But I can see the response in the server side.
Pretty similar way I invoked the request with
xmlHttpObj.open("GET","http://localhost:8080/ajax/demoExample.html",true);
and my URL is http://192.168.16.254:8080/ajax..., then also I am not able to see the response in my client side.
I know the best way to fix the problem.
I can invoke the request with
xmlHttpObj.open("GET","../ajax/demoExample.html",true);
xmlHttpObj.send();
then I don't have any problem with either localhost or IP address.
But still I think why is the difference between localhost and IP address in ajax requesting.
It's more of a security feature than a problem :
The same origin policy prevents a
document or script loaded from one
origin from getting or setting
properties of a document from another
origin.
localhost and 192.168.16.254 are considered different origins. The same goes for two hostnames that point to the same address as they could (and probably will) point to a different site/application on the same server. AFAIK the only way around this is to use iframe for content or JSONP for json. Although in your case relative URLs is the way to go.

Categories

Resources