0

I am just trying to write a simple node.js app that will be able to write to a file via post and access that file with the express.static().

var express = require('express'),
fs = require('fs')
url = require('url');
var app = express();

app.configure(function(){
  app.use('/public', express.static(__dirname + '/public'));  
  app.use(express.static(__dirname + '/public')); 
  app.use(express.bodyParser());
});

app.post('/receieve', function(request, respond) {
    filePath = __dirname + '/public/data.txt';
    fs.appendFile(filePath, request.body) 
});

app.listen(1110);  

I'm using postman chrome extension to test if my post is working correctly, but I'm receiving 'cannot POST /receive' when I try to send raw json. Any ideas of what the problem could be? Thank you!

user4815162342
  • 1,432
  • 2
  • 14
  • 21

1 Answers1

4

As go-oleg mentioned, there's a mismatch between the server-side route and the client-side request:

'/receive' !== '/receieve' // extra `e` in the route

You may also want to specify a format when appending request.body. Object#toString, which appendFile() will use, simply generates "[object Object]".

fs.appendFile(filePath, JSON.stringify(request.body));

And, you should .end() the response at some point:

fs.appendFile(filePath, JSON.stringify(request.body));
response.end();
fs.appendFile(filePath, JSON.stringify(request.body), function () {
    response.end();
});

You can also use .send() if you want to include a message in the response. It'll call .end().

Jonathan Lonowski
  • 112,514
  • 31
  • 189
  • 193
  • Big thanks for the heads up @Jonathan. It's now appending {}, though. Thanks again for your help! – user4815162342 Jul 30 '13 at 04:01
  • 1
    @user4815162342 Express checks the `Content-Type` before parsing: [`if ('application/json' != utils.mime(req)) return next();`](http://www.senchalabs.org/connect/json.html). So, make sure it's set to [`application/json`](http://stackoverflow.com/a/477819) in postman (seems you select "Raw" then "JSON" for this). – Jonathan Lonowski Jul 30 '13 at 04:11
  • Great information @Jonathan. also thanks for the addition of the call back for the response.end(). And I didn't know that send() called .end(). Thank you! – user4815162342 Jul 30 '13 at 04:15