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!

3
  • 3
    You have a typo in app.post('/receieve' Commented Jul 30, 2013 at 3:33
  • Thanks @go-oleg! I don't know how long I looked at this without noticing! Commented Jul 30, 2013 at 3:39
  • One of you should post an answer so @user4815162342 can accept and the question can fade away. Commented Jul 30, 2013 at 3:41

1 Answer 1

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().

Sign up to request clarification or add additional context in comments.

3 Comments

Big thanks for the heads up @Jonathan. It's now appending {}, though. Thanks again for your help!
@user4815162342 Express checks the Content-Type before parsing: if ('application/json' != utils.mime(req)) return next();. So, make sure it's set to application/json in postman (seems you select "Raw" then "JSON" for this).
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.