[英]Sanitizing illegal characters in a HTTP response header before importing into MongoDB in JSON format
在使用Node.js請求HTTP響應並將其導入MongoDB時,我注意到一個或兩個URL將包含包含非法字符的標頭(因為它們是使用的密鑰),這會在我嘗試導入MongoDB時使整個腳本崩潰。 一個例子如下:
{
"url": "divensurf.com",
"statusCode": 200,
"headers": {
"x-varnish": "2236710953 2236710300",
"vary": "Accept-Encoding,Cookie,X-UA-Device",
"cache-control": "max-age=7200, must-revalidate",
"x-cache": "V1HIT 2",
"content-type": "text/html; charset=UTF-8",
"page.ly": "v4.0",
"x-pingback": "http://divensurf.com/xmlrpc.php",
"date": "Thu, 21 Mar 2013 19:40:59 GMT",
"transfer-encoding": "chunked",
"via": "1.1 varnish",
"connection": "keep-alive",
"last-modified": "Thu, 21 Mar 2013 19:40:57 GMT",
"age": "2"
}
}
標題/鍵"page.ly"
會使腳本崩潰,因為它包含非法字符.
。 在將此文檔導入MongoDB之前,是否有任何方法可以通過刪除這些非法字符來清理包含在引號中的鍵/標題?
以下是我請求回復的代碼:
(function (i){
http.get(options, function(res) {
var obj = {};
obj.url = hostNames[i];
obj.statusCode = res.statusCode;
obj.headers = res.headers;
db.scrape.save(obj); // imports headers into MongoDB
}).on('error',function(e){
console.log("Error: " + hostNames[i] + "\n" + e.stack); // prints error stack onto console
})
})(i);
例如,它將從"page.ly"
到"pagely"
編輯:已解決。 檢查蓋爾的答案。
obj.headers={};
for(var item in res.headers){
obj.headers[ item.replace(/\./,'')] = res.headers[item];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.