簡體   English   中英

Http post與node.js並表達

[英]Http Post with node.js and express

我只是在嘗試編寫一個簡單的node.js應用程序,該應用程序將能夠通過發布寫入文件並使用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);  

我正在使用郵遞員 chrome擴展程序來測試我的帖子是否正常工作,但是當我嘗試發送原始json時我收到了“無法發布/接收”消息。 關於問題可能有什么想法? 謝謝!

正如go-oleg所述,服務器端路由和客戶端請求之間存在不匹配:

'/receive' !== '/receieve' // extra `e` in the route

您可能還希望在附加request.body時指定一種格式。 appendFile()將使用的Object#toString僅生成"[object Object]"

fs.appendFile(filePath, JSON.stringify(request.body));

並且,您應該在某點上使用.end() response

fs.appendFile(filePath, JSON.stringify(request.body));
response.end();
fs.appendFile(filePath, JSON.stringify(request.body), function () {
    response.end();
});

如果您想在response包含一條消息,也可以使用.send() 它將調用.end()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM