为什么我不能使用Express发布数据?

时间:2011-09-13 01:18:19

标签: node.js express

var locationJSON, locationRequest;
locationJSON = {
  latitude: 'mylat',
  longitude: 'mylng'
};
locationRequest = {
  host: 'localhost',
  port: 1234,
  path: '/',
  method: 'POST',
  header: {
    'content-type': 'application/x-www-form-urlencoded',
    'content-length': locationJSON.length
  }
};

var req;
req = http.request(options, function(res) {
  var body;
  body = '';
  res.on('data', function(chunk) {
    body += chunk;
  });
  return res.on('end', function() {
    console.log(body);
    callback(null, body);
  });
});
req.on('error', function(err) {
  callback(err);
});
req.write(data);
req.end();

另一方面,我有一个node.js服务器正在侦听端口1234,它永远不会收到请求。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您正在进行req.write(data)但据我所知,“数据”未在任何地方定义。您还将'content-length'标头设置为locationJSON.length,这是未定义的,因为locationJSON只有'latitude'和'longitude'属性。

正确定义'数据',并更改'内容类型'和'内容长度'以改为使用它。

var locationJSON, locationRequest;
locationJSON = {
  latitude: 'mylat',
  longitude: 'mylng'
};

// convert the arguments to a string
var data = JSON.stringify(locationJSON);

locationRequest = {
  host: 'localhost',
  port: 1234,
  path: '/',
  method: 'POST',
  header: {
    'content-type': 'application/json', // Set the content-type to JSON
    'content-length': data.length       // Use proper string as length
  }
};

/*
....
*/

req.write(data, 'utf8');  // Specify proper encoding for string
req.end();

如果这仍然不起作用,请告诉我。

相关问题