2016-05-12 14 views
0

Ich mache ein Skript, das eine API trifft (die ich leider nicht offen legen kann). Es ermöglicht mir, eine URL, Pfad, Port und ein paar boolesche Felder zu übermitteln.Nodejs: Wie kann ich eine Anfrage senden?

Mein Skript nimmt zuerst eine Liste von URLs auf (wobei sich jede URL in einer neuen Zeile befindet) und fügt sie in ein Array ein. Jede URL hat ihren eigenen Index.

Dann habe ich eine Funktion, die erstellt und eine HTTP-Anfrage veröffentlicht. Hier ist, was in der Anfrage gesendet wird: { "url": url, "path": "/", "port": "443", "live_scan": "false", "advanced": "true" }

wo url = array[counter]

Von dem, was ich in der Lage gewesen, durch verschiedene console.logs, um zu sehen, alles bis auf die eigentliche Schreibfunktion arbeitet.

An diesem Punkt, ich glaube, dass die JSON wird nie gesendet, wie meine Antwort immer undefined oder genauer gesagt ist, {"response":{}}

Hier ist mein vollständiger Code:

var http = require('http'); 
var fs = require('fs'); 
var EventEmitter = require('events').EventEmitter; 

// An object of options to indicate where to post to 

var post_options = { 
    host: 'localhost', 
    port: '8080', 
    path: '/api/scan', 
    method: 'POST' 
}; 




fs.readFile('urls.txt', function(err, data) { 

    //if (err) throw err; 
    //console.log(err); 
    var array = data.toString().split('\n'); 
    for (var i = 0; i < array.length - 1; i++) { 
     str = array[i]; 
     array[i] = str.slice(0, -1); 
    } 
    //console.log(array); 


    var emitter = new EventEmitter(); 
    var counter = 1, 
     n = array.length; 
    //console.log(n); 

    // Start with the first request 



    function PostRequest() { 
     var post_req = http.request(post_options, function(res) { 
      res.setEncoding('utf8'); 
      var body = ''; 
      res.on('data', function(chunk) { 
       body += chunk; 
      }); 
      res.on('end', function() { 
       //body = JSON.parse(body); 
       // Make sure it's working 
       console.log(body); 

       // ADD THE CALLBACK 
       // OR 
       // TRIGGER EVENT 
       //PostRequest(); 
       return emitter.emit('ResponseEnded'); 

      }); 
     }); 

     var url = array[counter]; 
     //console.log(url); 
     var catURL = { "url": url, "path": "/", "port": "443", "live_scan": "false", "advanced": "true" }; 
     console.log(catURL); 
     var jsonURL = JSON.stringify(catURL); 

     post_req.write(jsonURL, function(err) { 
      if (err) throw err; 
      //console.log(err); 

     }); 
     post_req.end(); 
    } 


    emitter.on('ResponseEnded', function() { 
     counter++; 
     if (counter < n) { 
      PostRequest(); 
     } else { 
      console.log('No more requests'); 
     } 
    }); 


    PostRequest(); 
}); 

Bin ich ein dumm machen Neuling Fehler? Oder ist das nur die völlig falsche Methode, um eine Anfrage zu stellen?

Danke für alle/jede Hilfe!

Oh, muss ich sagen, ich habe eine Möglichkeit, dies zu tun, wo ich manuell jede URL in das Array eingeben und nie einen Dateistream verwenden, und es funktioniert perfekt so, also verwende ich fs falsch? Hier

ist der Code für den hartcodierte URL-Array:

var http = require('http'); 
var fs = require('fs'); 
var EventEmitter = require('events').EventEmitter; 

// An object of options to indicate where to post to 

var post_options = { 
    host: 'localhost', 
    port: '8080', 
    path: '/api/scan', 
    method: 'POST', 
    headers: { 
     'Content-Type': 'application/json' 
    } 
}; 


var array = ['ssl.com', 'google.com', 'hamzakhan.org']; 



var emitter = new EventEmitter(); 
var counter = 0, 
    n = array.length; 
console.log(n); 

function PostRequest() { 
    var post_req = http.request(post_options, function(res) { 
     res.setEncoding('utf8'); 
     var body = ''; 
     res.on('data', function(chunk) { 
      body += chunk; 
     }); 
     res.on('end', function() { 
      body = JSON.parse(body); 
      // Make sure it's working 
      console.log(body.response.subject); 

      // ADD THE CALLBACK 
      // OR 
      // TRIGGER EVENT 
      //PostRequest(); 
      return emitter.emit('ResponseEnded'); 

     }); 
    }); 

    var url = array[counter]; 
    var catURL = { "url": url, "path": "/", "port": "443", "live_scan": "false", "advanced": "true" }; 
    post_req.write(JSON.stringify(catURL), function(err) { 
     //console.log(err); 
     post_req.end(); 
    }); 
} 


emitter.on('ResponseEnded', function() { 
    ++counter; 
    if (counter < n) { 
     PostRequest(); 
    } else { 
     console.log('No more requests'); 
    } 
}); 


// Start with the first request 
PostRequest(); 

Antwort

0

Ok, also alles, was ich hier getan habe, ist richtig. Mein einziges Problem war, dass ich vor einer Stunde gedacht hatte, dass das Senden von Kopfzeilen optional ist ... das ist es nicht.

habe ich vergessen, dies in post_options:

headers: { 
     'Content-Type': 'application/json' 
    } 

Danke für die Hilfe.

0

Hier ist ein Skript, das ich einmal verwendet:

var http = require('http'); 

var postData = querystring.stringify ({data:JSON.stringify ({timestamp:"823738632"})}); 

var options = { 
    hostname: 'www.google.com', 
    method: 'POST', 
    port: 80, 
    path: '/ncr', 
    headers: { 
     'Content-Type': 'application/x-www-form-urlencoded', 
     'Content-Length': Buffer.byteLength(postData) 
    } 
}; 

var sendRequest = function(options) 
{ 
    that = this; 
    that.req = http.request(options,function(res) 
    { 
     // console.log("Request began"); 
     var output = ''; 

     res.on('data', function (chunk) { 
      output += chunk; 
     }); 

     res.on('end', function() { 
      console.log(output); 
     }); 
    }); 

    that.req.on('error', function (err) 
    { 
     console.log("ServerError"); 
     console.log('error: ' + err.message); 
    }); 

    that.req.write(postData); 
    that.req.end(); 
}; 

sendRequest(options); 
+0

Das ist das gleiche, was ich mache. Sie haben nur einen einzelnen Datenstring, den Sie in die Anfrage eingeben, wo sich meine Änderungen pro Anfrage ändern. – hamza765

+0

Ich denke, der Trick liegt in der Zeile, die sagt req.write (postData); – RobertoNovelo

+0

Es akzeptiert nur korrekt formatierte Zeichenfolgen, z. data = in meinem Beispiel – RobertoNovelo

Verwandte Themen