在使用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"
编辑:已解决。检查盖尔的答案。
答案 0 :(得分:1)
obj.headers={};
for(var item in res.headers){
obj.headers[ item.replace(/\./,'')] = res.headers[item];
}