user4815162342
user4815162342

Reputation: 1688

Http Post with node.js and express

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!

Upvotes: 0

Views: 980

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123563

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

Upvotes: 4

Related Questions