2016-06-12 6 views
0

node.js에서 작동하도록 간단한 http 요청을받을 수없는 것 같습니다. 다음 코드는 아무것도 기록하지 않거나 오류를 인쇄하지 않고 멈 춥니 다.node.js http 모듈 사용

http = require 'http' 

callback = (response) -> 
    console.log 'callback' 
    str = '' 

    # another chunk of data has been recieved, so append it to `str` 
    response.on 'data', (chunk) -> 
    console.log 'data' 
    str += chunk 

    # the whole response has been recieved, so we just print it out here 
    response.on 'end', -> 
    console.log str 

http.get 'http://hacker-news.firebaseio.com/v0/topstories.json', callback 

생성 된 자바 스크립트 :

// Generated by CoffeeScript 1.10.0 
(function() { 
    var callback, http; 

    http = require('http'); 

    callback = function(response) { 
    var str; 
    console.log('callback'); 
    str = ''; 
    response.on('data', function(chunk) { 
     console.log('data'); 
     return str += chunk; 
    }); 
    return response.on('end', function() { 
     return console.log(str); 
    }); 
    }; 

    http.get('http://hacker-news.firebaseio.com/v0/topstories.json', callback); 

}).call(this); 

답변

0

기존 코드는 다른 URL을 잘 작동하는 것 같다. 그 URL은 특히 HTTP를 통해 작동하지 않는 것 같습니다, 적어도 curl을 사용하면 응답하지 않습니다. 브라우저에로드하면 HTTPS 버전으로 307 리디렉션이 반환되는 것 같습니다. 따라서 curl 또는 코드에 응답하지 않는 이유가 확실하지 않습니다.

는 상관없이, 당신은 아마 그래서 그냥 할 코드를 변경, 어쨌든 HTTPS URL을 사용하려면 : HTTP 및 HTTPS와 같은 '요청'또는 둘 모두를 지원

https = require 'https' 

callback = (response) -> 
    console.log 'callback' 
    str = '' 

    # another chunk of data has been recieved, so append it to `str` 
    response.on 'data', (chunk) -> 
    console.log 'data' 
    str += chunk 

    # the whole response has been recieved, so we just print it out here 
    response.on 'end', -> 
    console.log str 

https.get 'https://hacker-news.firebaseio.com/v0/topstories.json', callback 
0

에 한번 사용 LIB를 '요청 -약속'. 아래의 예는 잘 작동

,

var request = require('request'); 
request('https://www.xxxxx.com', function (error, response, body) { 
    if (!error && response.statusCode == 200) { 
    console.log(body); 
    } 
}) 

더 많은 정보 : https://www.npmjs.com/package/request