Using POST data to write to a local file using node.js and an expression

I am trying to simply handle simple POST requests and add data to a local file. However, when I try to send the POST source code from postman , for example, "hello world", what is actually added is [object Object] . I'm not sure what could be the reason for this if nothing should be interpreted as an object from both ends. Thanks!

 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('/receive', function(request, respond) { filePath = __dirname + '/public/data.txt'; fs.appendFile(filePath, request.body, function () { respond.end(); }); }); app.listen(8080); 
+4
source share
3 answers
 var express = require('express'), fs = require('fs') url = require('url'); var app = express(); app.use('/public', express.static(__dirname + '/public')); app.use(express.static(__dirname + '/public')); app.post('/receive', function(request, respond) { var body = ''; filePath = __dirname + '/public/data.txt'; request.on('data', function(data) { body += data; }); request.on('end', function (){ fs.appendFile(filePath, body, function() { respond.end(); }); }); }); app.listen(8080); 
+15
source

If you want to execute POST requests with regular urlencoded bodies, you do not want to use bodyParser (since you actually do not want to parse the body, you just want to transfer it to the file system). Think of just streaming pieces of data with req.pipe(writeableStreamToYourFile) .

If you want to download files, you can use bodyParser to do this, but it processes several files and writes them to disk for you, and you will need to iterate through req.files and copy them from the temporary directory to your target file.

+4
source

If you want to save Json data then the file must be **. Json type. Otherwise, try pasting it into a string and writing to a ** file. Txt. how

 var fs = require('fs'); var writer = fs.createWriteStream('output.txt'); response = { name: '', id: '' } writer.write(JSON.stringify(response)); 
+2
source

Source: https://habr.com/ru/post/1494589/


All Articles