2017-02-14 23 views
0

こんにちは、コールバックメソッドを使用してhttp経由で応答を取得しようとしています。しかし、私は多くの情報を得ることではなく、私のデータ:ノードJSのノードJSのHTTP要求コールバック

Request { 
    domain: null, 
    _events: 
    { error: [Function: bound ], 
    complete: [Function: bound ], 
    pipe: [Function] }, 
    _eventsCount: 3, 
    _maxListeners: undefined, 
    uri: 
    Url { 
    protocol: 'http:', 
    slashes: true, 
    auth: null, 
    host: 'localhost', 
    port: 80, 
    hostname: 'localhost', 
    hash: null, 
    search: '?filter=route_short_name', 
    query: 'filter=route_short_name', 
    pathname: '/php-rest/api.php/routes', 
    path: '/php-rest/api.php/routes?filter=route_short_name', 
    href: 'http://localhost/php-rest/api.php/routes?filter=route_short_name' }, 
    callback: [Function], 
    readable: true, 
    writable: true, 
    _qs: 
    Querystring { 
    request: [Circular], 
    lib: { formats: [Object], parse: [Function], stringify: [Function] }, 
    useQuerystring: undefined, 
    parseOptions: {}, 
    stringifyOptions: {} }, 
    _auth: 
    Auth { 
    request: [Circular], 
    hasAuth: false, 
    sentAuth: false, 
    bearerToken: null, 
    user: null, 
    pass: null }, 
    _oauth: OAuth { request: [Circular], params: null }, 
    _multipart: 
    Multipart { 
    request: [Circular], 
    boundary: '9ab5d31f-9896-4fb9-8f89-47e5501e9342', 
    chunked: false, 
    body: null }, 
    _redirect: 
    Redirect { 
    request: [Circular], 
    followRedirect: true, 
    followRedirects: true, 
    followAllRedirects: false, 
    followOriginalHttpMethod: false, 
    allowRedirect: [Function], 
    maxRedirects: 10, 
    redirects: [], 
    redirectsFollowed: 0, 
    removeRefererHeader: false }, 
    _tunnel: 
    Tunnel { 
    request: [Circular], 
    proxyHeaderWhiteList: 
     [ 'accept', 
     'accept-charset', 
     'accept-encoding', 
     'accept-language', 
     'accept-ranges', 
     'cache-control', 
     'content-encoding', 
     'content-language', 
     'content-location', 
     'content-md5', 
     'content-range', 
     'content-type', 
     'connection', 
     'date', 
     'expect', 
     'max-forwards', 
     'pragma', 
     'referer', 
     'te', 
     'user-agent', 
     'via' ], 
    proxyHeaderExclusiveList: [] }, 
    headers: { host: 'localhost' }, 
    setHeader: [Function], 
    hasHeader: [Function], 
    getHeader: [Function], 
    removeHeader: [Function], 
    method: 'GET', 
    localAddress: undefined, 
    pool: {}, 
    dests: [], 
    __isRequestRequest: true, 
    _callback: [Function], 
    proxy: null, 
    tunnel: false, 
    setHost: true, 
    originalCookieHeader: undefined, 
    _disableCookies: true, 
    _jar: undefined, 
    port: 80, 
    host: 'localhost', 
    path: '/php-rest/api.php/routes?filter=route_short_name', 
    httpModule: 
    { IncomingMessage: { [Function: IncomingMessage] super_: [Object] }, 
    METHODS: 
     [ 'ACL', 
     'BIND', 
     'CHECKOUT', 
     'CONNECT', 
     'COPY', 
     'DELETE', 
     'GET', 
     'HEAD', 
     'LINK', 
     'LOCK', 
     'M-SEARCH', 
     'MERGE', 
     'MKACTIVITY', 
     'MKCALENDAR', 
     'MKCOL', 
     'MOVE', 
     'NOTIFY', 
     'OPTIONS', 
     'PATCH', 
     'POST', 
     'PROPFIND', 
     'PROPPATCH', 
     'PURGE', 
     'PUT', 
     'REBIND', 
     'REPORT', 
     'SEARCH', 
     'SUBSCRIBE', 
     'TRACE', 
     'UNBIND', 
     'UNLINK', 
     'UNLOCK', 
     'UNSUBSCRIBE' ], 
    OutgoingMessage: { [Function: OutgoingMessage] super_: [Object] }, 
    ServerResponse: { [Function: ServerResponse] super_: [Object] }, 
    STATUS_CODES: 
     { '100': 'Continue', 
     '101': 'Switching Protocols', 
     '102': 'Processing', 
     '200': 'OK', 
     '201': 'Created', 
     '202': 'Accepted', 
     '203': 'Non-Authoritative Information', 
     '204': 'No Content', 
     '205': 'Reset Content', 
     '206': 'Partial Content', 
     '207': 'Multi-Status', 
     '208': 'Already Reported', 
     '226': 'IM Used', 
     '300': 'Multiple Choices', 
     '301': 'Moved Permanently', 
     '302': 'Found', 
     '303': 'See Other', 
     '304': 'Not Modified', 
     '305': 'Use Proxy', 
     '307': 'Temporary Redirect', 
     '308': 'Permanent Redirect', 
     '400': 'Bad Request', 
     '401': 'Unauthorized', 
     '402': 'Payment Required', 
     '403': 'Forbidden', 
     '404': 'Not Found', 
     '405': 'Method Not Allowed', 
     '406': 'Not Acceptable', 
     '407': 'Proxy Authentication Required', 
     '408': 'Request Timeout', 
     '409': 'Conflict', 
     '410': 'Gone', 
     '411': 'Length Required', 
     '412': 'Precondition Failed', 
     '413': 'Payload Too Large', 
     '414': 'URI Too Long', 
     '415': 'Unsupported Media Type', 
     '416': 'Range Not Satisfiable', 
     '417': 'Expectation Failed', 
     '418': 'I\'m a teapot', 
     '421': 'Misdirected Request', 
     '422': 'Unprocessable Entity', 
     '423': 'Locked', 
     '424': 'Failed Dependency', 
     '425': 'Unordered Collection', 
     '426': 'Upgrade Required', 
     '428': 'Precondition Required', 
     '429': 'Too Many Requests', 
     '431': 'Request Header Fields Too Large', 
     '451': 'Unavailable For Legal Reasons', 
     '500': 'Internal Server Error', 
     '501': 'Not Implemented', 
     '502': 'Bad Gateway', 
     '503': 'Service Unavailable', 
     '504': 'Gateway Timeout', 
     '505': 'HTTP Version Not Supported', 
     '506': 'Variant Also Negotiates', 
     '507': 'Insufficient Storage', 
     '508': 'Loop Detected', 
     '509': 'Bandwidth Limit Exceeded', 
     '510': 'Not Extended', 
     '511': 'Network Authentication Required' }, 
    Agent: { [Function: Agent] super_: [Object], defaultMaxSockets: Infinity }, 
    globalAgent: 
     Agent { 
     domain: null, 
     _events: [Object], 
     _eventsCount: 1, 
     _maxListeners: undefined, 
     defaultPort: 80, 
     protocol: 'http:', 
     options: [Object], 
     requests: {}, 
     sockets: {}, 
     freeSockets: {}, 
     keepAliveMsecs: 1000, 
     keepAlive: false, 
     maxSockets: Infinity, 
     maxFreeSockets: 256 }, 
    ClientRequest: { [Function: ClientRequest] super_: [Object] }, 
    request: [Function], 
    get: [Function], 
    _connectionListener: [Function: connectionListener], 
    Server: { [Function: Server] super_: [Object] }, 
    createServer: [Function], 
    Client: [Function: deprecated], 
    createClient: [Function: deprecated] }, 
    agentClass: 
    { [Function: Agent] 
    super_: 
     { [Function: EventEmitter] 
     EventEmitter: [Circular], 
     usingDomains: false, 
     defaultMaxListeners: [Getter/Setter], 
     init: [Function], 
     listenerCount: [Function] }, 
    defaultMaxSockets: Infinity }, 
    agent: 
    Agent { 
    domain: null, 
    _events: { free: [Function] }, 
    _eventsCount: 1, 
    _maxListeners: undefined, 
    defaultPort: 80, 
    protocol: 'http:', 
    options: { path: null }, 
    requests: {}, 
    sockets: {}, 
    freeSockets: {}, 
    keepAliveMsecs: 1000, 
    keepAlive: false, 
    maxSockets: Infinity, 
    maxFreeSockets: 256 } } 

マイノードJSコードは次のとおりです。

var http = require('http'); 
 

 
function getRoutes(callback){ 
 
\t var callback = request('http://localhost/php-rest/api.php/routes?filter=route_short_name', function(error, response, body, callback) { 
 
\t \t if (!error && response.statusCode == 200) { 
 

 
\t \t \t result = JSON.stringify(JSON.parse(body)); 
 
\t \t \t //console.log(result); 
 
\t \t \t //res.setHeader('Content-Type', 'application/json'); 
 
\t \t \t //res.send(result); 
 
\t \t \t return callback = result; 
 
\t \t } else { 
 
\t \t \t //res.end('Error: ' + error); 
 
\t \t \t return callback = error; 
 
\t \t } 
 
\t }); 
 
\t return callback; 
 
} 
 

 
app.get('/getRoutes', function(req, res) { 
 

 
\t var data = getRoutes(); 
 
\t console.log(data); 
 
\t //res.setHeader('Content-Type', 'application/json'); 
 
\t res.send(data); 
 
});

私は、コールバック(結果やエラーの内容を)したいです。 誰かが私にこれを手伝ってもらえると大変感謝します。

答えて

1

です。 requestモジュールにコールバックパラメータがありません。hereを参照してください。

var http = require('http'); 

function getRoutes(callback){ 
    request('http://localhost/php-rest/api.php/routes?filter=route_short_name', function(error, response, body) { 
     if (!error && response.statusCode == 200) { 
      result = JSON.stringify(JSON.parse(body));   
      return callback(result, false); 
     } else {    
      return callback(null, error);; 
     } 
    }); 
} 

app.get('/getRoutes', function(req, res) { 

    getRoutes(function(err, data){ 
     if(err) return res.send(err);  
     res.send(data); 
    }); 

}); 
+1

その仕事:私はコールバックについてもっと学びます。ありがとう^^ –

1

コードにコールバックに問題があります。私はあなたがコールバックを使用する方法を学ぶべきだと思います。ここでこれを使用すると、コールバックを使用して関数を記述する必要があります方法ですあなたは右のコールバックをしなかったあなたのためのチュートリアルhttps://www.tutorialspoint.com/nodejs/nodejs_callbacks_concept.htm

var http = require('http'); 

    function getRoutes(callback){ 
     request('http://localhost/php-rest/api.php/routes?filter=route_short_name', function(error, response, body) { 
      if (!error && response.statusCode == 200) { 

       result = JSON.stringify(JSON.parse(body)); 

       return callback(null, result); 
      } else { 
       return callback(error, null); 
      } 
     }); 
    } 

    app.get('/getRoutes', function(req, res) { 

     getRoutes(function(err, data){ 
      if(!err){ 

        res.send(data); 
      } 
      else{ 
        res.send(err); 
      } 

     }); 

    }); 
0

(おっと遅いIM)

var request = require('request'); 

function getRoutes(callback){ 

    request('http://localhost/php-rest/api.php/routes?filter=route_short_name', (error, response, body) => { 

     if (!error && response.statusCode == 200) { 

      result = JSON.stringify(JSON.parse(body)); 

      callback(null, result); 

     } else { 

      callback(error, null); 

     } 
    }); 

}; 

app.get('/getRoutes', (req, res) => { 

    getRoutes(function(err, data) { 

     if (err) console.log('error', err)//error handling 

     console.log(data); 

    }); 

});