在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ node搭建本地服務(wù)器,接受post請(qǐng)求,返回爬蟲爬取的數(shù)據(jù),log上都顯示成功

node搭建本地服務(wù)器,接受post請(qǐng)求,返回爬蟲爬取的數(shù)據(jù),log上都顯示成功,但是前端接到的數(shù)據(jù)是catch中的數(shù)據(jù)。

用node搭建了一個(gè)本地服務(wù)器,主要的功能是,接受Post請(qǐng)求,然后去sf上面爬數(shù)據(jù)返回,顯示的情況是,在cmd里面打印出來,顯示的是爬取成功,但是前臺(tái)接到的確實(shí)catch中的error2。
下面是代碼。

圖片描述

圖片描述

圖片描述

let http = require("http");
let url = require("url"); //解析get請(qǐng)求
let query = require("querystring"); //post請(qǐng)求相關(guān)
// let creep = require('./creep');

http.createServer(function(request,response){
    //post
    response.setHeader("Access-Control-Allow-Origin","*");
    response.setHeader(
          "Access-Control-Allow-Methods",
          "PUT, GET, POST, DELETE, HEAD, PATCH"
    );

    // var params = url.parse(request.url,true);

    let postData = "";
    request.addListener("data",function(chunk){
        postData += chunk;
    });

    //end 表示全部body接受完畢
    request.addListener("end",function(){
        creepDataForUrl().then(function(creepRes){
            response.end(creepRes);
        },function(e){
            console.log("fail");
        }).catch(function(e){
            console.log("error:" +JSON.stringify(e));
        })        
    });
}).listen(8011);

const https = require('https');
const cheerio = require('cheerio');

function creepDataForUrl(){
    return new Promise(function(resolve,rej){
        https.get('https://segmentfault.com', (res) => {
                  var data = '';
                  res.on('data', (chunk) => {
                    data += chunk;
                  });
                  res.on('end', () => {
                      let temp = getDataFromHtml(data);
                      console.log(temp.length);
                      resolve(temp);
                  })
            }).on('error', (e) => {
                  console.log("這里出錯(cuò)了:" + JSON.stringify(e));
                  rej && rej(e);
            });
    });
}

function getDataFromHtml(htmlData){
    let $ = cheerio.load(htmlData);
    let items = $("div.news-item.stream__item.clearfix");
    let resAry=[];
    items.each(function(index,item){
        let el = $(item);
        resAry.push({
            title:el.find(".news__item-info a").first().text(),
        });
    });
    return resAry;
}




回答
編輯回答
心夠野

ok,問題我找到了,在確實(shí)在catch里捕獲了一個(gè)錯(cuò)誤,使用JSON.stringify是看不到內(nèi)容的(這個(gè)我不知道為什么,有可能js的error對(duì)象里面的屬性是不可枚舉的?),我直接打印e.message,得到的提示是:first argument must be a string or buffer. 我在success里面第一個(gè)參數(shù)時(shí)數(shù)組,所以才會(huì)進(jìn)入catch,改成.tostring之后就可以了。

2018年9月10日 22:49