node.js - 如何在 Node.js 中获取发布数据?

标签 node.js

Server1.js

var data = querystring.stringify({
    imageName: reqImgName
  });

var options = {
              host: 'localhost',
              port: 4321,
              path: '/image',
              method: 'POST',
              headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Content-Length': data.length
                }
            };

server2.js

http.createServer(function(req, res){
  var reqMethod=req.method;
  var request = url.parse(req.url, true);
  var pathName = request.pathname;
  console.log('Path name is '+pathName);
  if (reqMethod=='POST' && pathName == '/image') {

   //here i need my server1 data..how can i get here.
   } 

}).listen(4321);

最佳答案

var postData = '';
req.on('data', function(datum) {
  postData += datum;
});

req.on('end', function() {
  //read postData
});

您没有收到任何发布数据,因为您没有在 server1.js 中发送任何数据。尝试向请求正文写入一些数据

var req = http.request(options, function(res) {

});


req.write('data=somedata');

调试 server2 的另一种方法是让浏览器向/image 发起 POST 请求

关于node.js - 如何在 Node.js 中获取发布数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18051709/

相关文章:

node.js - 如何将 Node.js 作为后台进程运行并且永不死亡?

javascript - Node mysql插入当前日期

node.js - 无法识别Jenkins powershell ng

javascript - mongo findAndUpdateOne 在我的例子中失败了

javascript - 在 sequelize node.js 中添加关联与添加自定义外键列

javascript - 从输出文件中删除 Webpack Bootstrap

node.js - npm install 安装,但 node_modules 为空

node.js - NodeJS 与 Express 作为 HTML --> PDF 生成的服务器。能有效率吗?

php - 无法从 Nest 服务器获取访问 token

node.js - 如何使用child_process执行多条命令?