使用 POST 数据通过 node.js 和 express 写入本地文件 [英] Using POST data to write to local file with node.js and express

查看:37
本文介绍了使用 POST 数据通过 node.js 和 express 写入本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅处理简单的 POST 请求并将数据附加到本地文件.但是,当我尝试使用 postman,如'hi world',实际附加的是[object Object].如果在任何一端都不应将任何内容解释为对象,我不确定是什么导致了这种情况.谢谢!

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 actually appended is [object Object]. I'm not sure what could be causing this if nothing should be interpreted as an object on either end. Thank you!

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);

推荐答案

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);

这篇关于使用 POST 数据通过 node.js 和 express 写入本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆