I'm trying to POST data from an iOS app to Node.js/Express. I cannot get it to work; Node/Express just appears to ignore my request when I try from my app. However, if I navigate to the same URL I'm trying to POST to in a web browser, Node/Express responds.
This is my Node/Express code that handles the incoming request:
var express = require('express');
var app = express.createServer();
app.configure(function(){
app.use(express.bodyParser());
});
app.get('/', function(req, res) {
res.write('nothing to see here...');
res.end();
});
app.get('/test', function(req, res) {
console.log('handling post!');
console.log(JSON.stringify(req.body));
res.end();
});
And this is how I'm trying to POST JSON to Node:
// Create request data.
NSString* jsonData = @"{\"test\" : \"someMoreTest\"}";
NSData* requestData = [jsonData dataUsingEncoding:NSUTF8StringEncoding];
// Create URL to POST jsonData to.
NSString* urlString = @"http://www.mysite.com/test";
NSURL* url = [NSURL URLWithString:urlString];
// Create request.
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody: requestData];
// Send request synchronously.
NSURLResponse* response = [[NSURLResponse alloc] init];
NSError* error = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// Check result.
if (error != nil)
{
NSLog(@"submitted request!");
}
else {
NSString* errorLogFormat = @"request failed, error: %@";
NSLog(errorLogFormat, error);
}
As I mentioned earlier, if I navigate to http://www.mysite.com/test in my browser, my console output from Node is the following:
handling post!
{}
However, when I try to post from my iOS app, I get no console app - it's almost as if Node never sees the incoming POST request. And even more baffling - I can't get any error data on the iOS app side - the error is nil
. Any ideas what I'm doing wrong here?
In Express's routing framework, app.get() only responds to GET requests, POSTs are ignored and probably result in a 404.
You can use post() or any() instead.
I can't comment on the objective C portion, but I will suggest Nc -l 0.0.0.0 80 {or another port) o see what's going on.