Using POST data to write to local file with node.js and express

前端 未结 3 1614
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 15:37

I\'m trying to just handle simple POST requests and append the data to a local file. However, when I try to POST raw text with postman, such as \'hi world\', what\'s actuall

相关标签:
3条回答
  • 2020-12-01 15:53
    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);
    
    0 讨论(0)
  • 2020-12-01 16:02

    If you want to store Json data then file should be of **.Json type. Otherwise try casting it into string and write into **.txt file. Like

    var fs = require('fs');
    var writer = fs.createWriteStream('output.txt');
    response = {
    name: '',
    id: ''
    }
    writer.write(JSON.stringify(response));
    
    0 讨论(0)
  • 2020-12-01 16:09

    If you want to do POST requests with regular urlencoded bodies, you don't want to use bodyParser (since you don't actually want to parse the body, you just want to stream it to the filesystem). Consider just streaming the chunks of data with req.pipe(writeableStreamToYourFile).

    If you want to do file uploads, you can use bodyParser for that, but it handles multiple files and writes them to disk for you and you would need to iterate through req.files and copy them from a temporary directory to your target file.

    0 讨论(0)
提交回复
热议问题