简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM