在Node.js中提出请求时提示使用URL

时间:2015-12-18 18:44:14

标签: javascript node.js request httprequest

我想要做的是提示用户输入网址,输入的网址我想发出http请求。但是我不断收到错误消息 “TypeError:无法读取未定义的属性'parent'。”

当我将网址直接硬编码到请求中时,它可以正常工作。只有一次我试图提示我收到错误。

var answer = '';
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question("Enter a url you'd like to scrape: ", function(answer) {
  // TODO: Log the answer in a database
  console.log("This is the url you enetered:", answer);
  rl.close();
});

request(answer, function(error,response,html){
     //some code here
});

TIA!

1 个答案:

答案 0 :(得分:0)

看起来你正试图让事情异步执行,但他们正在以同步的方式工作。这似乎更符合您的想法:

'use strict';

const readline = require('readline');
const request = require('request');

let answer = '';

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question("Enter a url you'd like to scrape: ", function(answer) {
  // TODO: Log the answer in a database
  console.log("This is the url you enetered:", answer);
  rl.close();
  crawl(answer, function (error, response, html) {
    console.log(html);
    // or whatever else you want
  });
});

//use wrapper function
function crawl(answer, callback){
  request(answer, function (error, response, html) {
    callback(error, response, html);
  });
}

您也可以使用request(answer, function...)内部的rl.question()调用,但如果您使用其他功能进行包装,则可以获得更好的可读性,并在其他地方再次使用