Cheerio刮痧与蓝鸟承诺

问题描述 投票:0回答:1

为什么这段代码不起作用?我明白了

TypeError: $ is not a function

test.js

'use strict';

var Promise = require('bluebird');
var request = require('request-promise');
var cheerio = require('cheerio');

module.exports = {
    get: function () {

        return new Promise(function (resolve, reject) {
            var options = {
                uri: 'https://www.example.com',
                transorm: function (body) {
                    return cheerio.load(body);
                }
            };

            request(options)
                .then(function ($) {
                    // Error happens here
                    $('#mydivid').text();
                    resolve();
                })
                .catch(function (error) {
                    console.log(error);
                    reject(error);
                });
        });
    }
}
node.js bluebird cheerio request-promise
1个回答
1
投票

我又看了一眼,发现了这个问题。你的options对象如下:

 var options = {
                uri: 'https://www.example.com',
                transorm: function (body) {
                    return cheerio.load(body);
                }
 };

你使用transorm而不是transform。因此它返回的html内容字符串而不是cheerio.load(body)。将它改为transform它会起作用。

 var options = {
                uri: 'https://www.example.com',
                transform: function (body) {
                    return cheerio.load(body);
                }
 };
© www.soinside.com 2019 - 2024. All rights reserved.