How to access POST data sent from a browser to Rikulo Steam Server - ajax

I ask the browser to POST JSON data to the stream v0.5.5 server using ajax. In the server side, how can I receive the data from the ajax request?
My client:(Google Chrome)
void ajaxSendJSON() {
HttpRequest request = new HttpRequest(); // create a new XHR
// add an event handler that is called when the request finishes
request.onReadyStateChange.listen((_) {
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
// data saved OK.
print(request.responseText); // output the response from the server
}
});
// POST the data to the server
var url = "/news";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.send(mapTOJSON()); // perform the async POST
}
String mapTOJSON() {
print('mapping json...');
var obj = new Map();
obj['title'] = usrTitle.value == null ? "none" : usrTitle.value;
obj['description'] = usrDesc.value == null ? "none" : usrDesc.value;
obj['photo'] = usrPhoto.value == "none";
obj['time'] = usrTime==null ? "none" : usrTime.value;
obj['ip']= '191.23.3.1';
//obj["ip"] = usrTime==null? "none":usrTime;
print('sending json to server...');
return Json.stringify(obj); // convert map to String i.e. JSON
//return obj;
}
My server:
void serverInfo(HttpConnect connect) {
var request = connect.request;
var response = connect.response;
if(request.uri.path == '/news' && request.method == 'POST') {
response.addString('welcome from the server!');
response.addString('Content Length: ');
response.addString(request.contentLength.toString());
} else {
response.addString('Not found');
response.statusCode = HttpStatus.NOT_FOUND;
}
connect.close();
}
Again, I don't want the browser to ask for data from the server!
What am I doing is to asking the browser to submit the JSON data via ajax, and I just don't know how the server (Rikulo Stream v0.5.5) gets the "content" of data? All code is written in Google Dart Language M3. No Javascript!

POST is not supported well in Dart SDK, but Dart team planned to enhance it. Please stargaze it here: issue 2488.
On the other hand, since what you handle is JSON, you can listen to HttpRequest (I'm assuming the latest SDK) and convert List to String and then to JSON. Rikulo Commons provides a utility to simplify the job as follows:
import "package:rikulo_commons/io.dart";
IOUtil.readAsJson(request, onError: connect.error).then((jsonValue) {
//handle it here
});

Related

Taking value from text-field and sending it with AJAX request Javascript

I am trying to sync both client-side and server-side scripts that the client intakes a value from the textbox and sends it to the server, upon which the server displays that input as a cookie.
Here is the code that I have so far
function loadCookie() {
//[1] make a new request object
var xhttp = new XMLHttpRequest();
//[2] set the request options
xhttp.open("GET", "index.html", true);
//[3] define what you will do when you ge a response (callback)
xhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
document.getElementById("input_response").innerHTML = this.responseText;
}
};
//[4] finally send out the request
xhttp.send();
}
I have the and the button but I am having issue of the page re-loading itself instead of taking the value of the input and showing it as a cookie in the server. I'm suspecting it is having to do with the URL by the index.html

How to get each http body updates on angular Http request?

I'm using an express api (my back-end) and an angular app (my front-end).
One express js end point (let's call it '/foo') is processing a lot of files,
i send data using res.write() after each treatment so the http response body is update.
I would like to get this update on my angular app.
I was using ajax in a previous version and it worked fine with ajax call :
xhrFields: {
// Getting on progress streaming response
onprogress: function(e)
{
var progressResponse;
var response = e.currentTarget.response;
if(lastResponseLength === false)
{
progressResponse = response;
lastResponseLength = response.length;
}
else
{
progressResponse = response.substring(lastResponseLength);
lastResponseLength = response.length;
}
actualResponse += progressResponse
}
Unfortunatly i found nothing to get partial http body. I tried to use 'reportProgress' Parameter but it's not working.
For some more context my front-end angular code:
service.ts :
setHolidaysDirectory(holidaysKey: string, path: string): Observable<Object>{
const setHolidayDirectoryStreamHttpRequest =
new HttpRequest('POST', 'http://localhost:8089/holidays/pictures/edit', { 'key': holidaysKey,
'path': path
}, {headers: this._httpHeaders, reportProgress: true, responseType: 'text'});
// pipe stream answer
return this._http.request(setHolidayDirectoryStreamHttpRequest);
}
and my component just call the service and subscribe :
this._holidaysService
.setHolidaysDirectory(key, finalHolidaysForm.path)
.subscribe((stream) => {
console.log('new answer');
console.log(stream);
}, error => console.log(error));
But unfortunatly i got empty answer and all the http body is recovered after res.end() (server side)
Can anyone help pls !
Thank a lot !

How to download from firebase storage string written by putString() in web application [duplicate]

I uploaded a raw String 'Test' to the firebase storage using the sample provided here and it went through successfully.
But when I tried to "download" the string I uploaded, using the sample below, apparently he only example on how to download data from firebase storage it returns the url of the string file.
storageRef.child('path/to/string').getDownloadURL().then(function(url) {
// I get the url of course
}).catch(function(error) {
// Handle any errors
});
How do I get the contents of the file from the callback url which is 'Test' (The string I uploaded.)
The short answer is that in the Web Storage SDK you can only get a download URL that represents that data. You'll need to "download" the file using an XMLHttpRequest (or equivalent):
storageRef.child('path/to/string').getDownloadURL().then(function(url) {
var XMLHttp = new XMLHttpRequest();
XMLHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
var response = xmlHttp.responseText; // should have your text
}
XMLHttp.open("GET", url, true); // true for asynchronous
XMLHttp.send(null);
}).catch(function(error) {
// Handle any errors from Storage
});

AJAX Request gets cancelled with AngularJS and Spring Security

We're running an external Grails server-application with the Spring Security plugin.
The front-end is running locally on AngularJS.
Whenever I try to login, the request is immediately canceled.. Remarkably AngularJS sends a GET request first with the OPTIONS method; this returns a 200 OK response just fine.
The actual POST request does never reach the server though... what could possibly cancel my request?
The following code:
$scope.login = function() {
$http.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
$scope.loggingIn = true;
// Setup Config
var data = {
j_username: $scope.user.email,
j_password: $scope.user.password
}
var config = {method: 'POST', url: serverUri+'/j_spring_security_check/', data: data};
// Dispatch HTTP Request
$http(config)
.success(function(data, status, headers, config) {
if (data.status) {
// successful login
User.isLogged = true;
User.username = data.username;
}
else {
User.isLogged = false;
User.username = '';
}
$scope.loggingIn = false;
console.log("NOICE!");
})
.error(function(data, status, headers, config) {
$scope.loggingIn = false;
User.isLogged = false;
User.username = '';
if (status == 0) {
// Request got cancelled
console.log("Request got cancelled.");
return;
}
});
}
This is what the canceled request looks like: http://i.stack.imgur.com/kiWnb.png
This is what the OPTIONS request looks like: http://i.stack.imgur.com/FAj96.png
Apparently Chrome does not handle 302 Moved temporarily status codes efficiently when queried by AngularJS in my situation. Firefox properly shows there is a response where Chrome just shows the request as canceled with no response information whatsoever.
This question is solved, but there is still a mystery as to WHY AngularJS does not work. See my question here:
AngularJS $http ajax does not follow Location header

RestSharp on Windows Phone with Request Parameters

I'm working on Windows phone client for one service with Oauth1 API.
In API docs I have something like this:
url: http://example.com/iphone/json/users/
method: GET
parameters:
page_num=[int] - page number, >=1, default=1.
For default page num everything works well:
RestClient HabraClient = new RestClient("http://habrahabr.ru");
HabraClient.Authenticator = OAuth1Authenticator.ForProtectedResource("xxx", "yyyyyy", App.Tokens.Key, App.Tokens.Secret);
var TokenRequest = new RestRequest("/iphone/json/users/", Method.GET);
HabraClient.ExecuteAsync(TokenRequest, (response =>
{
try
{
if (response.StatusCode == HttpStatusCode.OK)
{
When I execute this request I receive correct response with data.
But if I add parameter (uncomment TokenRequest.AddParameter("page_num", 2); ) I receive "Invalid signature". I have tried to send both int and string parameter.
var TokenRequest = new RestRequest("/iphone/json/users/", Method.GET);
TokenRequest.AddParameter("page_num", 2);
HabraClient.ExecuteAsync(TokenRequest, (response =>
{
try
{
if (response.StatusCode == HttpStatusCode.OK)
{
I receive message "Invalid signature". I have tried string parameter too:
TokenRequest.AddParameter("page_num", "2");
API provider told me, that I have a problem with signature base
string http://oauth.net/core/1.0/#sig_base_example
So, how can i view it? Or maybe you can help me to solve all this
problem?
I think you are breaking the request structure... better to check the request over Fiddler, but try to write something like
var TokenRequest = new RestRequest("/iphone/json/users/?page_num=2", Method.GET);
instead of
var TokenRequest = new RestRequest("/iphone/json/users/", Method.GET);
TokenRequest.AddParameter("page_num", 2);
Hope, it would help.

Resources