2011-09-13 44 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。 –

相關問題