解析来自http请求的JSON响应?

时间:2016-01-10 12:52:28

标签: javascript json node.js parsing httprequest

我正在使用“请求”'模块,来自我的Nodejs应用程序,向网站发出http请求并以JSON格式返回html。但是,我尝试使用JSON.parse()函数,但它似乎没有工作?

我已经控制台记录了响应以检查请求是否正常工作,它是..但是解析并没有返回任何内容?

有什么想法吗?代码:

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)
    })

1 个答案:

答案 0 :(得分:1)

仅仅因为请求指定你想要json回来并不意味着bbc将用json响应。看起来bbc正在使用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-CDN