node.js请求从express调用时返回不同

时间:2017-10-29 06:55:42

标签: javascript node.js express

我有一个函数using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace App1 { class DataPageViewModel : INotifyPropertyChanged { private FormItem _formItem; public FormItem FormItem { get { return _formItem; } set { _formItem = value; OnPropertyChanged("FormItem"); } } public event PropertyChangedEventHandler PropertyChanged; public DataPageViewModel() { this.FormItem = new FormItem(); } protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } ,它接受​​一个URL和一个回调函数。它调用URL,获取内容,解析它(getPropertyData),转换它(buildDataObject),并调用回调:

transformData

当我直接调用此函数时:

const request = require('request');
const cheerio = require('cheerio');
const express = require('express');

var getPropertyData = function(url, callback) {
  request(url, function(err, res, body) {
    var $ = cheerio.load(body);
    console.log("Received data (html length): " + body.length)

    var data = buildDataObject($);
    console.log("Parsed data (object length): " + Object.keys(data).length);

    var property = transformData(data);

    callback(property);
  });
};

var buildDataObject = function($) {
  data = {}

  // Populate data object with data from response.
  // will return {} if no data was found to parse.

  return data;
};

var transformData = function(data) {
  if(Object.keys(data).length != 0) {
    return {"message":"success"}
  } else {
    return {"message":"no data received"}
  }
}

以下内容将打印到控制台:

getPropertyData(url, function(result) {
  console.log(result);
})

但是,当我从快速路线定义中调用此函数时:

Received data (html length): 323948
Parsed data (object length): 72
<Expected result>

这会打印到控制台:

var app = express()

...

app.get('/property', function(req, response) {
  getPropertyData(req.query.url, function(result) {
    console.log(result);
    response.json(result);
  });
});

为什么在调用相同的URL时收到的数据在直接调用函数时长度超过300k,但在快速路由中调用函数时低于20k?我需要做些什么才能确保在快速通道内拨打时获得相同的300k +线路?

0 个答案:

没有答案