2011-09-13 32 views
0
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,它从来没有收到请求。有任何想法吗?为什么我不能使用Express来发布数据?

+0

看起来'req.write'需要一个字符串,数组或缓冲区。所以也许我应该将我的JSON转换为数组? – Shamoon

+0

通过JSON.stringify()运行它并将Content-Type设置为application/json。 –

回答

1

你在做req.write(data),但据我所见,'数据'没有在任何地方定义。您还将'content-length'标题设置为locationJSON.length,这是未定义的,因为locationJSON只具有“纬度”和“经度”属性。

正确定义'data',并改变'content-type'和'content-length'来代替。

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

让我知道这是否仍然无效。

+1

将Content-Type设置为application/json,然后执行req.write(JSON.stringify(data));是不是更有意义? –

+0

他没有指定他的服务器是如何设置的,所以我不想改变太多的东西,但是如果服务器可以解码使用内容类型应用程序/ json的参数也可以。 – loganfsmyth

+1

这篇文章的标题说Express,并且他在示例中没有使用Express的任何功能;所以,我假设接收请求的服务器是Express。它是bodyParser中间件,支持application/json解码并将信息放入req.body。 –

相关问题