Still confused about using XMLHTTPRequest cross domain - xmlhttprequest

I need to POST data to a server in a different domain. That server is using SSL and expects the data to be in the form of a JSON string. I am attempting to do this from javascript.
I create the data and use JSON.stringify() to get it into the correct format. Then I send it as follows:
var url = "https://api.postageapp.com/v.1.0/send_message.json";
http=new XMLHttpRequest();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json");
http.setRequestHeader("Connection", "close");
// create the data in a data structure named post_data
var JSONText = JSON.stringify(post_data);
http.send(JSONText);
Doing a packet trace I see my client do a handshake with the server but then twice the server replies with "Encrypted alert" including the last time it sends a packet back. The browser debugger always shows a 405 - Method Now Allowed error.
What am I missing to get this to work? When they try it within their domain it runs fine.

You need server to return a HTTP Header like that:
header('Access-Control-Allow-Origin: *');
Live example:
Making cross domain JavaScript requests using XMLHttpRequest or XDomainRequest

You cannot do a cross domain post like that.
Alternative is to use Server side proxy (read this link for a nice explanation as to why you can't do that) or iframe approach.

Strictly speaking it should not be possible (due to security issues) however using a workaround called JSONP you can achieve this with a RESTful web service.
See the link below.
http://en.wikipedia.org/wiki/JSONP
MS has some code you can download somewhere on the internet with specific bindings the code is called.
JSONPBehaviour.cs
JSONPBindingElement.cs
JSONPBindingExtension.cs
JSONPEncoderFactory.cs

Related

How to distinguish between GET and POST

I'm writing a simple api for training using express. Here's my testing code:
var express = require('express');
var app = express();
app.post("/api/:var_name", function(req, res) {
res.send(req.params.var_name);
});
is simply testing to see if POST is working. When I call http://localhost:3000/api/1 I get Cannot GET /api/1, so the server is obviously interpreting the POST request as GET, what do I need to do to call POST instead?
Anything you call in the address bar of your browser will be sent via get. This is due to the fact that post-messages (and almost all other methods) do have a body-part. But there is no way for your browser to send additional information inside the body of the http packet.
If you want to test your routes for any method other than GET I would suggest you download a tool like postman.
https://www.getpostman.com/
BEWARE: This is my preference. You can of curse also use text based browsers like curl to test it.
The server interprets the request according to the verb you set in the HTTP request. If no method/verb is specified it is interpreted as GET(not sure about this part).
When you call that URL, you need to use the method as well. For example if you use the fetch API, you can call it like:
fetch(url, {method:"POST"})
If you're entering it in your browser and expect it to be interpreted as a post request, it's not. All browser url requests are GET. Use a tool like Postman to call different HTTP verbs. It's really useful when creating such APIs.
You can check out this answer on details of how to add body and headers to a post request: Fetch: POST json data

Intercept Requests With Custom Responses in PhantomJS?

Is there a way to intercept a resource request and give it a response directly from the handler? Something like this:
page.onRequest(function(request){
request.reply({data: 123});
});
My use case is for using PhantomJS to render a page that makes calls to my API. In order to avoid authentication issues, I'd like to intercept all http requests to the API and return the responses manually, without making the actual http request.
onResourceRequest almost does this, but doesn't have any modification capabilities.
Possibilities that I see:
I could store the page as a Handlebars template, and render the data into the page and pass it off as the raw html to PhantomJS (instead of a URL). While this would work, it would make changes difficult since I'd have to write the data layer for each webpage, and the webpages couldn't stand alone.
I could redirect to localhost, and have a server there that listens and responds to the requests. This assumes that it would be ok to have an open, un-authenticated version of the API on localhost.
Add the data via page.evaluate to the page's global window object. This has the same problems as #1: I'd need to know a-priori what data the page needs, and write server side code unique to each page.
I recently needed to do this when generating pdfs with phantom js.
It's slightly hacky, but seems to work.
var page = require('webpage').create(),
server = require('webserver').create(),
totallyRandomPortnumber = 29522,
...
//in my actual code, totallyRandomPortnumber is created by a java application,
//because phantomjs will report the port in use as '0' when listening to a random port
//thereby preventing its reuse in page.onResourceRequested...
server.listen(totallyRandomPortnumber, function(request, response) {
response.statusCode = 200;
response.setHeader('Content-Type', 'application/json;charset=UTF-8');
response.write(JSON.stringify({data: 'somevalue'}));
response.close();
});
page.onResourceRequested = function(requestData, networkRequest) {
if(requestData.url.indexOf('interceptme') != -1) {
networkRequest.changeUrl('http://localhost:' + totallyRandomPortnumber);
}
};
In my actual application I'm sending some data to phantomjs to overwrite request/responses, so I'm doing more checking on urls both in server.listen and page.onResourceRequested.
This feels like a poor-mans-interceptor, but it should get you (or whoever this may concern) going.

RESTlet redirect sending browser riap URI

I'm using RESTlet to handle PUT requests from a browser and after a successful PUT, I want to redirect the browser to different web page.
Seems like a standard PUT->REDIRECT->GET to me, but I'm not figuring out how to do it in my RESTlet resource.
Here is my code after the PUT has done the requested work:
getResponse().redirectSeeOther("/account");
However that results in the browser getting:
Response Headers
Location riap://application/account
Of course, "riap" protocol is meaningless to the browser and "application" is not a server name. It seems like there ought to be a way to send a redirect back to the browser without building the entire URL in my redirectSeeOther() call. Building the URL seems like to could be error prone.
Is there an easy way to redirect without building the whole URL from the ground up?
Thanks!
Sincerely,
Stephen McCants
Although I am not 100% sure in what type of class you are trying to do this.
Try :
Reference reference = getRequest().getRootRef().clone().addSegment("account");
redirectSeeOther(reference);
I usually also then set the body as
return new ReferenceList(Arrays.asList(reference)).getTextRepresentation();
but that may not be necessary for all clients, or at all. I will usually use this style in a class that extends ServerResource - Restlet (2.0.x or 2.1.x).

Use AWS S3 success_action_redirect policy with XHR

I'm using signed POST to upload file directly to amazon S3. I had some trouble with the signature of the policy using PHP but finally fixed it and here is the sample of code.
This xhr request is send in javascript and I'm waiting for an answer from amazon. At first I was using success_action_status setting it to 201 to get the XML response.
What I'd like to do is using the success_action_redirect to call a script on my server to create a record in the database.
The reason why is that I could create the record in the database and if anything wrong happen at this stage I can return an error message directly at this point. Also it saves me another ajax request to my server.
So I've tried to set this up specifying the success_action_redirect to http:\\localhost\callback.php where I have a script that is waiting for some parameters.
But it looks like this script is never called and the response of the xhr.send() is empty.
I think it's a cross-browser issue and I'm wondering if it would be possible to use jsonp somehow to pass-by this?
Any ideas?
UPDATE
Apparently xhr is following redirect natively so it should work but when I specified the success_action_redirect it returns error Server responded with 0 code.
At first I thought it was because the redirect URL was on my local server so I've changed it to an accessible server but no chance.
Anyone knows why it's returning this error message?
I also run into this problem. It seems like nobody has a solution to this like this
maybe the best workaround i have found is something like this.
It seems thet the only workaround includes a second xhr-request to execute the callback manually. therefore the
success_action_status
should be used. Witht his you will get a 201 response if the upload was successful and you can start a second request for the actual callback. For me it looks like the only possible solution at the moment.
Any other solutions?

Cannot load Google Images from its API using jQuery getJSON

My code is below:
$.getJSON('https://ajax.googleapis.com/ajax/services/search/images?q=Google&v=1.0',
function(json) {
alert(json);
})​
You can try this code here: http://jsbin.com/ofaru3/edit
The ajax is error
imagesFailed to load resource
How cna I fix this problem? Thanks!
You need &callback=? on the URL there to trigger JSONP, like this:
$.getJSON('https://ajax.googleapis.com/ajax/services/search/images?q=Google&v=1.0&callback=?',
function(json) {
alert(json);
});
You can test it out here. Without the &callback? it's trying to fetch the data from a remote domain with an XmlHttpRequest (AJAX) and failing/being blocked due to the same origin policy. This is exactly the type of situation JSONP is for.
From the $.getJSON() docs:
JSONP
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.