being a Node newbie, I seem to be struggling with some very basic steps. Can someone point me in the right direction please?
Essentially, I'm trying to send an input from an iOS (Objective-C) client to a Node.js server, but somehow not able to parse the http message body. In fact the data being posted from the client is not even appearing in the request if I log the same in the POST API on the server. I can confirm the endpoints are correct since other logs are getting printed... Here's my iOS and Node code - seems to be pretty straightforward...
Appreciate your inputs...
iOS code:
- (IBAction)sendUsername:(id)sender
{
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://MYURL:PORT/registerUser"]];
NSDictionary *sentData = [[NSDictionary alloc] initWithObjectsAndKeys:#"socool", #"username", nil];
NSError *theError = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:sentData options:NSJSONWritingPrettyPrinted error:&theError];
[postRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[postRequest setHTTPMethod:#"POST"];
[postRequest setHTTPBody:postData];
// Have tried with both - initWithRequest and with sendSyncRequest - both dont show the req.body on the server...
// NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:postRequest delegate:self];
NSError *returnedError = nil;
NSURLResponse *urlResponse = [[NSURLResponse alloc] init];
NSData *dataResponse = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&urlResponse error:&returnedError];
}
Node.js code:
app.post('/registerUser', function(req, res) {
console.log("Request to register new user received"); // This gets printed successfully...
body = [];
body = Buffer.concat(body).toString();
console.log("Targeted output is: ", req.body.username); // req.body itself keeps coming as undefined.
});
It looks like you're using ExpressJS. If that's the case, prior to setting up your route with app.post, did you specify a bodyParser?
Take a look at this: http://expressjs.com/en/api.html
Specifically, the 'req.body' section.
Express relies upon a middleware that is going to intercept the request, parse it, and then fill req.body with it.
Related
I open a file download from a remote API on my webpage via window.open(). The API (a Flask server) has error handling and returns the error message if there's an internal server error, like this:
#app.errorhandler(502) //all other errors are handled the same way, including 500, etc.
#crossdomain(origin='*')
def bad_gateway_error(error):
return "Bad Gateway Error - Please make sure you're using a properly formatted file! Details: " + str(error), 200
I want to display this error on my site instead of redirecting to the error page. I'm trying to catch it via:
try {
window.open("https://API/receivedoc?timestamp="+timestamp,"_self")
} catch(e) {
filerootdiv.querySelector('.output').innerHTML = String(e);
}
This however does nothing (tested in Chrome). How could I catch the error when I'm using window.open? I guess it might be because in the error handling I return a 200 message so that the string I return actually gets returned instead of just crashing the server (this needs to stay this way as it's working just fine with all the other errors when I'm not trying to return a file). The issue is that I can't tell if the API request would return a file or a string before doing a window.open().
UPDATE
I've tried implementing:
let new_window = window.open("https://flaskmin.run.aws-usw02-pr.ice.predix.io/receivedoc?timestamp="+timestamp,"_self")
newWindow.onerror = function() {
filerootdiv.querySelector('.output').innerHTML = "Error!";
However this still only opens a new window with the error. I guess it's because of the error handling on the server side (I cannot change this). Can I somehow probe the content of new_window before redirecting to it, and just not open it if it's just a string containing the word 'error'?
I'm attempting to write a C# WebSocket server for an application that interacts upon browser input.
This is the code:
class Program {
static void Main(string[] args) {
var listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 42001);
listener.Start();
using(var client = listener.AcceptTcpClient())
using(var stream = client.GetStream())
using(var reader = new StreamReader(stream))
using(var writer = new StreamWriter(stream)) {
while (!reader.EndOfStream) {
String line = reader.ReadLine();
if (new Regex("^GET").IsMatch(line)) {
line = reader.ReadLine();
if (new Regex("^Sec-WebSocket-Key: ").IsMatch(line)) {
String key = new Regex("(^Sec-WebSocket-Key\\: |\\r\\n)").Replace(line, "");
key = Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")));
writer.WriteLine("HTTP/1.1 101 Switching Protocols");
writer.WriteLine("Upgrade: websocket");
writer.WriteLine("Connection: Upgrade");
writer.WriteLine("Sec-WebSocket-Accept: " + key);
writer.WriteLine("Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits");
writer.WriteLine("WebSocket-Origin: http://127.0.0.1");
writer.WriteLine("WebSocket-Location: ws://localhost:42001/websocket");
writer.WriteLine("");
}
}
}
}
listener.Stop();
}
}
... and:
var ws = new WebSocket('ws://localhost:42001/websocket');
ws.onopen = function() {
console.log('connected');
};
ws.onmessage = function(e) {
console.log(e.data);
};
ws.onerror = function(e) {
console.log(e);
};
ws.onclose = function() {
console.log("closed");
};
On execution, the TPCListener successfully accepts the TCPClient and reads the incoming HTTP request. It parses the Key, generates the correct Accept token, but the JS - window native - WebSocket seems to have gone flat out bonkers: it does not answer no matter what it receives.
I would expect it throwing an error upon sending a HTTP/1.1 400 Bad Request, but nothing at all happens. It just goes mute.
Checking out Chrome Dev Tools' Networking tab, I do only see the websocket outgoing GET request, but no incoming packets - is that supposed to happen?
If I forcefully close the application, WebSocket throws this exception:
WebSocket connection to 'ws://localhost:42001/websocket' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET.
What am I missing here? Thank you all in advance.
Also, I'm not using Net.WebSockets because it is available since .NET 4.5, and my application targets systems from Windows 7 to the current build of Windows 10.
well... how far does your C# code get? My first bet would be on buffering - you don't flush the writer or stream, so I would expect them to be holding onto data while stuck in the top of the while loop, but frankly it shouldn't be a while loop in the first place - you only get one handshake per socket, not many. You could try adding flushes after the blank line, and you should make sure the Socket itself has buffering disabled (NoDelay = true;) - but: fundamentally this isn't a good way to write a web-socket server. Apart from anything else, the data will cease to be text if the handshake succeeds, so having a TextReader is a very bad thing. Frankly, you should be dealing with raw Socket / byte[] data here, IMO (having implemented this very thing several times).
i am trying to create an ios appplication which can data from website and can show me in an application.Is there any way though which i can get data from a website and show that data into my ios application?? please guide if something you have for me
Most sites expect a GET request.
Open a network connection to the server on port 80. Send the text "GET /rest_of_url" and read the text that comes back. It is up to you what you do with the response.
Try it with a simple raw terminal like putty to see how the server responds before going too deep coding.
Secure sites with https will take more work.
If I understand what you want, you can get datas from your URL with the following code
-(void) getDataWithCompletionHandler:(void(^ _Nonnull)(void))completion{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"GET"];
[request setURL:[NSURL URLWithString:self.url]];
[self setRequestProperty:request];
[[[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration] delegate:self delegateQueue:Nil] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable retour, NSError * _Nullable error) {
[self handleResponse:completion withDatas:data andTheHTTPResponse:retour];
}] resume];
}
I'm using the pushwoosh phonegap plugin for push notifications. After successful registration I need to store the device ID that the registration used in the "hwid" parameter so that I can target push notifications that I send with this same device ID. This works great on Android since it seems the phonegap device.uuid is the same ID that the pushwoosh plugin is sending to their servers. However, on ios the device.uuid returns a different ID than what is sent to pushwoosh. I can see from the Xcode console log the hwid that the plugin is sending to pushwoosh but cannot figure out where they are getting this ID from and how to access the same ID within phonegap.
EDIT: I was hoping the getRemoveNotificationStatus function would return this info but it actually returns less than the registerDevice callback.
UPDATE: Ok, from digging through their plugin code I see where they are constructing this ID that they send to their servers. Not sure why this ID isn't accessible through the phonegap plugin since this is the ID that I ultimately need to have in order to target a push notification to the specific device.
Their code:
(NSString *) uniqueDeviceIdentifier{
NSString *macaddress = [self macaddress];
NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
NSString *stringToHash = [NSString stringWithFormat:#"%#%#",macaddress,bundleIdentifier];
NSString *uniqueIdentifier = [self stringFromMD5:stringToHash];
return uniqueIdentifier;
}
- (NSString *) uniqueGlobalDeviceIdentifier{
// >= iOS6 return identifierForVendor
UIDevice *device = [UIDevice currentDevice];
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"6.1")) {
if ([device respondsToSelector:#selector(identifierForVendor)] && [NSUUID class]) {
NSUUID *uuid = [device identifierForVendor];
return [uuid UUIDString];
}
}
// Fallback on macaddress
NSString *macaddress = [self macaddress];
NSString *uniqueIdentifier = [self stringFromMD5:macaddress];
return uniqueIdentifier;
}
Are you sure that you need the hwid?
When I use the Pushwoosh Remote API to send push messages to individual devices I target using the "devices" tag and then just supply the deviceToken of the devices I wish to message.
The device token is easily accessible as it's part of the status-return from the plugin (status['deviceToken']).
As I posted here.
I found a work-around for anyone who needs this. Just open up the class "PWRequest.m" in xcode. Add the code below just under "[dict setObject:hwid forKey:#"hwid"];" in the NSMutableDictionary method.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"hwidfile2.txt"];
NSLog(#"From Echo Class File Path: %#", filePath);
NSString *str = hwid;
This will save a text file to your local app directory in which you can access from your Javascript code. For example, you can use this JS code to access and print the hwid to the console. Just call the 'readPwfile(filename)' function, passing in the name of your file as the function argument.
function readPWFile(fileName){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
fileSystem.root.getFile(fileName, null, gotReadFileEntry, fail);
});
function gotReadFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
//readDataUrl(file);
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log('Reading file... hwig Result: '+evt.target.result);
};
reader.readAsText(file);
}
}
I am trying to use Apple's UIAutomation to write unit tests for an iOS Application that has a server-side component. In order to setup the test server in various states (as well as simulate two clients communicating through my server), I would like to issue HTTP get requests from within my javascript-based test.
Can anyone provide an example of how to either issue HTTP GET requests directly from within UIAutomation javascript tests, or how to invoke a shell script from within my UIAutomation javascript tests?
FWIW, most of the core objects made available by all browsers are missing within the UIAutomation runtime. Try to use XMLHTTPRequest for example and you will get an exception reporting that it cannot find the variable.
Thanks!
Folks,
I was able to work around this by sending HTTP requests to the iOS client to process and return the results in a UIAlertView. Note that all iOS code modifications are wrapped in #if DEBUG conditional compilation directives.
First, setup your client to send out notifications in the event of a device shake. Read this post for more information.
Next, in your iOS main app delegate add this code:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(deviceShakenShowDebug:)
name:#"DeviceShaken"
object:nil];
Then add a method that looks something like this:
- (void) deviceShakenShowDebug:(id)sender
{
if (!self.textFieldEnterDebugArgs)
{
self.textFieldEnterDebugArgs = [[[UITextField alloc] initWithFrame:CGRectMake(0, 0, 260.0, 25.0)] autorelease];
self.textFieldEnterDebugArgs.accessibilityLabel = #"AlertDebugArgsField";
self.textFieldEnterDebugArgs.isAccessibilityElement = YES;
[self.textFieldEnterDebugArgs setBackgroundColor:[UIColor whiteColor]];
[self.tabBarController.selectedViewController.view addSubview:self.textFieldEnterDebugArgs];
[self.tabBarController.selectedViewController.view bringSubviewToFront:self.textFieldEnterDebugArgs];
}
else
{
if ([self.textFieldEnterDebugArgs.text length] > 0)
{
if ([self.textFieldEnterDebugArgs.text hasPrefix:#"http://"])
{
[self doDebugHttpRequest:self.textFieldEnterDebugArgs.text];
}
}
}
}
- (void)requestDidFinishLoad:(TTURLRequest*)request
{
NSString *response = [[[NSString alloc] initWithData:((TTURLDataResponse*)request.response).data
encoding:NSUTF8StringEncoding] autorelease];
UIAlertView *resultAlert =
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Request Loaded",#"")
message:response
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK",#"")
otherButtonTitles:nil] autorelease];
resultAlert.accessibilityLabel = #"AlertDebugResult";
[resultAlert show];
}
This code will add a UITextField to the very top view controller after a shake, slapped right above any navigation bar or other UI element. UIAutomation, or you the user, can manually enter a URL into this UITextField. When you shake the device again, if the text begins with "http" it will issue an HTTP request in code (exercise for the reader to implement doDebugHttpRequest).
Then, in my UIAutomation JavaScript file, I have defined the following two functions:
function httpGet(url, delayInSec) {
if (!delayInSec) delay = 1;
var alertDebugResultSeen = false;
var httpResponseValue = null;
UIATarget.onAlert = function onAlert(alert) {
httpResponseValue = alert.staticTexts().toArray()[1].name();
alert.buttons()[0].tap();
alertDebugResultSeen = true;
}
var target = UIATarget.localTarget();
var application = target.frontMostApp();
target.shake(); // bring up the input field
application.mainWindow().textFields()["AlertDebugArgsField"].setValue(url);
target.shake(); // send back to be processed
target.delay(delayInSec);
assertTrue(alertDebugResultSeen);
return httpResponseValue;
}
function httpGetJSON(url, delayInSec) {
var response = httpGet(url, delayInSec);
return eval('(' + response + ')');
}
Now, in my javascript file, I can call
httpGet('http://localhost:3000/do_something')
and it will execute an HTTP request. If I want JSON data back from the server, I call
var jsonResponse = httpGetJSON('http://localhost:3000/do_something')
If I know it is going to be a long-running call, I call
var jsonResponse = httpGetJSON('http://localhost:3000/do_something', 10 /* timeout */)
I've been using this approach successfully now for several weeks.
Try performTaskWithPathArgumentsTimeout
UIATarget.host().performTaskWithPathArgumentsTimeout("/usr/bin/curl", "http://google.com", 30);
Just a small correction. The answer that suggests using UIATarget.host().performTaskWithPathArgumentsTimeout is an easy way to make a request on a URL in iOS 5.0+, but the syntax of the example is incorrect. Here is the correct way to make this call:
UIATarget.host().performTaskWithPathArgumentsTimeout("/usr/bin/curl", ["http://google.com"], 30);
The "[" around the "args" param is important, and the test will die with an exception similar to the following if you forget the brackets:
Error: -[__NSCFString count]: unrecognized selector sent to instance
Here is a fully working example that hits google.com and logs all the output:
var result = UIATarget.host().performTaskWithPathArgumentsTimeout("/usr/bin/curl", ["http://www.google.com"], 30);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
UIALogger.logDebug("stderr: " + result.stderr);
+1 for creative use of "shake()". However, that's not an option for some projects, especially those that actually use the shake feature.
Think outside the box. Do the fetching with something else (Python, Ruby, node.js, bash+wget, etc). Then, you can use the pre-canned response and auto-generate the ui-test.js on the fly by including that dynamically generated json payload as the "sample data" into the test. Then you simply execute the test.
In my opinion, the test is the test, leave that alone. The test data you are using, if it's that dynamic, it ought to be separated from the test itself. By doing it this way of fetching / generating JSON, and referencing it from the test, you can update that JSON however often you like, either immediately right before every test, or on a set interval like when you know the server has been updated. I'm not sure you would want to generate it while the test is running, that seems like it would create problems. Taking it to the next level, you could get fancy and use functions that calculate what values ought to be based on other values, and expose them as "dynamic properties" of the data, rather than that math being inside the test, but at that point I think the discussion is more of an academic one rather than the practical one of how.
Apple has recently updated UIAutomation to include a new UIAHost element for performing a task on the Host that is running the instance of Instruments that is executing the tests.