我使用Nodejs应用程序中的'requestify‘模块向站点发出http请求,并以JSON格式返回html。但是,我正在尝试使用JSON.parse()函数,但它似乎不起作用?
我在控制台上记录了响应,以检查请求是否正常,它是否is..but解析没有返回任何内容?
有什么想法吗?代码:
parse.js
var requestify = require('requestify');
var fs = require('fs')
var obj;
var url = 'http://www.bbc.co.uk'
requestify.request(url, {
method: 'GET',
cookies: {
'examplename':'examplevalue'
},
dataType: 'json'
})
.then(function(response){
var pattern = /href=.{1,50}/g
obj = JSON.parse('{"filter": "href.+/-", "flags": "g"}')
obj.filter = new RegExp(obj.filter, obj.flags)
var r = response.match(obj.filter)
console.log(r)
})发布于 2016-01-10 13:08:18
仅仅因为请求指定您希望json返回,并不意味着bbc将使用json进行响应。看上去英国广播公司正在用html做出回应,这使得JSON.parse可能会失败。
$ curl -H "Content-Type: application/json" http://www.bbc.co.uk -v > out.log
* About to connect() to www.bbc.co.uk port 80 (#0)
* Trying 212.58.244.71... connected
* Connected to www.bbc.co.uk (212.58.244.71) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8y zlib/1.2.3
> Host: www.bbc.co.uk
> Accept: */*
> Content-Type: application/json
>
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0< HTTP/1.1 200 OK
< Server: nginx
< Content-Type: text/html; charset=utf-8
< ETag: W/"2266d-K1zKA7z5pAya6M49nLj/pg"
< X-Frame-Options: SAMEORIGIN
< x-origin-route: xrt-lb
< Content-Length: 140909
< Date: Sun, 10 Jan 2016 13:06:27 GMT
< Connection: keep-alive
< Set-Cookie: BBC-UID=c566b912a5f755d32356f02df1d767d43a09776757d42496ea40c7c28dc4415c0curl/7.19.7%20(universal-apple-darwin10.0)%20libcurl/7.19.7%20OpenSSL/0.9.8y%20zlib/1.2.3; expires=Thu, 09-Jan-20 13:06:27 GMT; path=/; domain=.bbc.co.uk
< X-Cache-Action: HIT
< X-Cache-Hits: 123
< X-Cache-Age: 9
< Cache-Control: private, max-age=0, must-revalidate
< Vary: Accept-Encoding, X-CDNhttps://stackoverflow.com/questions/34705573
复制相似问题