简体   繁体   English

Http post与node.js并表达

[英]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(). 我只是在尝试编写一个简单的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);  

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. 我正在使用邮递员 chrome扩展程序来测试我的帖子是否正常工作,但是当我尝试发送原始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: 正如go-oleg所述,服务器端路由和客户端请求之间存在不匹配:

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

You may also want to specify a format when appending request.body . 您可能还希望在附加request.body时指定一种格式。 Object#toString , which appendFile() will use, simply generates "[object Object]" . appendFile()将使用的Object#toString仅生成"[object Object]"

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

And, you should .end() the response at some point: 并且,您应该在某点上使用.end() response

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 . 如果您想在response包含一条消息,也可以使用.send() It'll call .end() . 它将调用.end()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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