Come effettuare chiamate REST remote all'interno di Node.js? qualche ricciolo?


189

In Node.js , oltre all'utilizzo del processo figlio per effettuare chiamate CURL , esiste un modo per effettuare chiamate CURL all'API REST del server remoto e ottenere i dati di ritorno?

Devo anche impostare l'intestazione della richiesta per la chiamata REST remota , e anche interrogare la stringa in GET (o POST).

Lo trovo: http://blog.nodejitsu.com/jsdom-jquery-in-5-lines-on-nodejs

ma non mostra alcun modo per la stringa di query POST.


Risposte:


212

Guarda a http.request

var options = {
  host: url,
  port: 80,
  path: '/resource?id=foo&bar=baz',
  method: 'POST'
};

http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
}).end();

3
Quindi, anche se è POST, aggiungo anche i dati nella stringa di query?
— murvinlai,

3
@murvinlai non sono sicuro. Vai a leggere i documenti, l'origine, le specifiche HTTP. Non un esperto in quella regione.
— Raynos,

15
Una cosa da notare è che non inserisci http o https nella voce host, ad es. Var options = {host: graph.facebook.com ....} non {host: http: graph.facebook.com}. Questo mi ha fatto inciampare per alcuni cicli. (Vedi sotto). Queste sono entrambe ottime risposte. Grazie a entrambi.
— binarygiant

9
Posso solo sottolineare che se la risposta è lunga, l'utilizzo di res.on ('data', ..) non è sufficiente. Credo che il modo corretto sia avere anche res.on ('fine' ..) per sapere quando hai ricevuto tutti i dati. Quindi puoi elaborare.
— Xerri il

4
Questa è una risposta molto vecchia: per coloro che scrivono il nodo js oggi useresti sicuramente npmjs.com/package/node-fetch o altri pacchetti basati su API di recupero, basati sullo standard Fetch. Vedi la mia risposta qui sotto.
— salpa il

94

Che ne dici di usare la richiesta - Client HTTP semplificato .

Modifica febbraio 2020: la richiesta è stata deprecata, quindi probabilmente non dovresti più utilizzarla.

Ecco un OTTENERE:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body) // Print the google web page.
     }
})

OP voleva anche un POST:

request.post('http://service.com/upload', {form:{key:'value'}})

1
Funziona bene con google.com ma restituisce "RequestError: Error: socket hang up" quando si richiede l'API del grafico di Facebook. Per favore guida, grazie!
— Dynamic Remo,

Questo modulo contiene molti problemi!
— Pratik Singhal,

Come posso passare un parametro di richiesta mentre consumo un'API REST in questo modo?
— vdenotaris,

2
A partire dall'11 febbraio 2020, la richiesta è completamente DEPRECATA. Puoi vederlo nel sito Web github.com/request/request#deprecated
— Sadiel

Qualche guida su quali neofiti dovrebbero usare? Sto filtrando attraverso MOLTI esempi che usano questo.
— Steve3p0

36

Guarda http://isolasoftware.it/2012/05/28/call-rest-api-with-node-js/

var https = require('https');

/**
 * HOW TO Make an HTTP Call - GET
 */
// options for GET
var optionsget = {
    host : 'graph.facebook.com', // here only the domain name
    // (no http/https !)
    port : 443,
    path : '/youscada', // the rest of the url with parameters if needed
    method : 'GET' // do GET
};

console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');

// do the GET request
var reqGet = https.request(optionsget, function(res) {
    console.log("statusCode: ", res.statusCode);
    // uncomment it for header details
//  console.log("headers: ", res.headers);


    res.on('data', function(d) {
        console.info('GET result:\n');
        process.stdout.write(d);
        console.info('\n\nCall completed');
    });

});

reqGet.end();
reqGet.on('error', function(e) {
    console.error(e);
});

/**
 * HOW TO Make an HTTP Call - POST
 */
// do a POST request
// create the JSON object
jsonObject = JSON.stringify({
    "message" : "The web of things is approaching, let do some tests to be ready!",
    "name" : "Test message posted with node.js",
    "caption" : "Some tests with node.js",
    "link" : "http://www.youscada.com",
    "description" : "this is a description",
    "picture" : "http://youscada.com/wp-content/uploads/2012/05/logo2.png",
    "actions" : [ {
        "name" : "youSCADA",
        "link" : "http://www.youscada.com"
    } ]
});

// prepare the header
var postheaders = {
    'Content-Type' : 'application/json',
    'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
};

// the post options
var optionspost = {
    host : 'graph.facebook.com',
    port : 443,
    path : '/youscada/feed?access_token=your_api_key',
    method : 'POST',
    headers : postheaders
};

console.info('Options prepared:');
console.info(optionspost);
console.info('Do the POST call');

// do the POST call
var reqPost = https.request(optionspost, function(res) {
    console.log("statusCode: ", res.statusCode);
    // uncomment it for header details
//  console.log("headers: ", res.headers);

    res.on('data', function(d) {
        console.info('POST result:\n');
        process.stdout.write(d);
        console.info('\n\nPOST completed');
    });
});

// write the json data
reqPost.write(jsonObject);
reqPost.end();
reqPost.on('error', function(e) {
    console.error(e);
});

/**
 * Get Message - GET
 */
// options for GET
var optionsgetmsg = {
    host : 'graph.facebook.com', // here only the domain name
    // (no http/https !)
    port : 443,
    path : '/youscada/feed?access_token=you_api_key', // the rest of the url with parameters if needed
    method : 'GET' // do GET
};

console.info('Options prepared:');
console.info(optionsgetmsg);
console.info('Do the GET call');

// do the GET request
var reqGet = https.request(optionsgetmsg, function(res) {
    console.log("statusCode: ", res.statusCode);
    // uncomment it for header details
//  console.log("headers: ", res.headers);


    res.on('data', function(d) {
        console.info('GET result after POST:\n');
        process.stdout.write(d);
        console.info('\n\nCall completed');
    });

});

reqGet.end();
reqGet.on('error', function(e) {
    console.error(e);
});

1
Come accedo ai valori da d ??? d = {"data": [{"id": 1111, "name": "peter"}]}. come ottenere il valore del nome?
— Pietro,

2
riuscito a ottenere valori usando var thed = JSON.parse (d); console.log ("l'id è:" + thed.data [0] .id); Ma qualche volta ricevo "Fine inaspettata dell'input"
— peter

33

Uso node-fetch perché utilizza l' API fetch () familiare (se sei uno sviluppatore web ) . fetch () è il nuovo modo per effettuare richieste HTTP arbitrarie dal browser.

Sì, so che questa è una domanda js sul nodo, ma non vogliamo ridurre il numero di sviluppatori che le API devono memorizzare e comprendere e migliorare la riutilizzabilità del nostro codice javascript? Il recupero è uno standard, quindi che ne dici di convergere su quello?

L'altra cosa bella di fetch () è che restituisce una Promessa javascript , quindi puoi scrivere un codice asincrono come questo:

let fetch = require('node-fetch');

fetch('http://localhost', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: '{}'
}).then(response => {
  return response.json();
}).catch(err => {console.log(err);});

Il recupero sostituisce XMLHTTPRequest . Ecco qualche informazione in più .


problema con la node-fetchscrittura di API è che funziona solo con URL completo e non funziona con URL relativi.
— Sebastian,


5

Axios

Un esempio (axios_example.js) che utilizza Axios in Node.js:

const axios = require('axios');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;

app.get('/search', function(req, res) {
    let query = req.query.queryStr;
    let url = `https://your.service.org?query=${query}`;

    axios({
        method:'get',
        url,
        auth: {
            username: 'the_username',
            password: 'the_password'
        }
    })
    .then(function (response) {
        res.send(JSON.stringify(response.data));
    })
    .catch(function (error) {
        console.log(error);
    });
});

var server = app.listen(port);

Assicurati che nella directory del tuo progetto:

npm init
npm install express
npm install axios
node axios_example.js

È quindi possibile testare l'API REST Node.js utilizzando il browser in: http://localhost:5000/search?queryStr=xxxxxxxxx

Allo stesso modo puoi pubblicare post, come:

axios({
  method: 'post',
  url: 'https://your.service.org/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

SuperAgent

Allo stesso modo è possibile utilizzare SuperAgent.

superagent.get('https://your.service.org?query=xxxx')
.end((err, response) => {
    if (err) { return console.log(err); }
    res.send(JSON.stringify(response.body));
});

E se vuoi fare l'autenticazione di base:

superagent.get('https://your.service.org?query=xxxx')
.auth('the_username', 'the_password')
.end((err, response) => {
    if (err) { return console.log(err); }
    res.send(JSON.stringify(response.body));
});

Rif:


5

Per utilizzare le funzionalità Async / Await più recenti

https://www.npmjs.com/package/request-promise-native

npm install --save request
npm install --save request-promise-native

//codice

async function getData (){
    try{
          var rp = require ('request-promise-native');
          var options = {
          uri:'https://reqres.in/api/users/2',
          json:true
        };

        var response = await rp(options);
        return response;
    }catch(error){
        throw error;
    }        
}

try{
    console.log(getData());
}catch(error){
    console.log(error);
}

4

un altro esempio: per questo è necessario installare il modulo di richiesta

var request = require('request');
function get_trustyou(trust_you_id, callback) {
    var options = {
        uri : 'https://api.trustyou.com/hotels/'+trust_you_id+'/seal.json',
        method : 'GET'
    }; 
    var res = '';
    request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            res = body;
        }
        else {
            res = 'Not Found';
        }
        callback(res);
    });
}

get_trustyou("674fa44c-1fbd-4275-aa72-a20f262372cd", function(resp){
    console.log(resp);
});

4
var http = require('http');
var url = process.argv[2];

http.get(url, function(response) {
  var finalData = "";

  response.on("data", function (data) {
    finalData += data.toString();
  });

  response.on("end", function() {
    console.log(finalData.length);
    console.log(finalData.toString());
  });

});

3

Non ne ho trovato nessuno con cURL, quindi ho scritto un wrapper attorno a node-libcurl e si può trovare su https://www.npmjs.com/package/vps-rest-client .

Fare un POST è così:

var host = 'https://api.budgetvm.com/v2/dns/record';
var key = 'some___key';
var domain_id = 'some___id';

var rest = require('vps-rest-client');
var client = rest.createClient(key, {
  verbose: false
});

var post = {
  domain: domain_id,
  record: 'test.example.net',
  type: 'A',
  content: '111.111.111.111'
};

client.post(host, post).then(function(resp) {
  console.info(resp);

  if (resp.success === true) {
    // some action
  }
  client.close();
}).catch((err) => console.info(err));

2

Se hai Node.js 4.4+, dai un'occhiata a reqclient , ti consente di effettuare chiamate e registrare le richieste in stile cURL , in modo da poter controllare e riprodurre facilmente le chiamate all'esterno dell'applicazione.

Restituisce gli oggetti Promessa anziché passare semplici callback, in modo da poter gestire il risultato in modo più "fashion" , concatenare il risultato facilmente e gestire gli errori in modo standard. Rimuove anche molte configurazioni di plateplate su ogni richiesta: URL di base, timeout, formato del tipo di contenuto, intestazioni predefinite, parametri e associazione di query nell'URL e funzionalità di base della cache.

Questo è un esempio di come inizializzarlo, effettuare una chiamata e registrare l'operazione con lo stile arricciatura :

var RequestClient = require("reqclient").RequestClient;
var client = new RequestClient({
    baseUrl:"http://baseurl.com/api/", debugRequest:true, debugResponse:true});
client.post("client/orders", {"client": 1234, "ref_id": "A987"},{"x-token": "AFF01XX"});

Questo accederà alla console ...

[Requesting client/orders]-> -X POST http://baseurl.com/api/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json

E quando la risposta viene restituita ...

[Response   client/orders]<- Status 200 - {"orderId": 1320934}

Questo è un esempio di come gestire la risposta con l'oggetto promessa:

client.get("reports/clients")
  .then(function(response) {
    // Do something with the result
  }).catch(console.error);  // In case of error ...

Naturalmente, può essere installato con: npm install reqclient.


1

Puoi usare curlrequest per impostare facilmente a che ora della richiesta vuoi fare ... puoi anche impostare le intestazioni nelle opzioni per " falsificare " una chiamata del browser.


1

Avviso: dall'11 febbraio 2020, la richiesta è completamente obsoleta.

Se si implementa con i dati del modulo, per ulteriori informazioni ( https://tanaikech.github.io/2017/07/27/multipart-post-request-using-node.js ):

var fs = require('fs');
var request = require('request');
request.post({
  url: 'https://slack.com/api/files.upload',
  formData: {
    file: fs.createReadStream('sample.zip'),
    token: '### access token ###',
    filetype: 'zip',
    filename: 'samplefilename',
    channels: 'sample',
    title: 'sampletitle',
  },
}, function (error, response, body) {
  console.log(body);
});

0

Ho trovato il superagente molto utile, ad esempio è molto semplice

const superagent=require('superagent')
superagent
.get('google.com')
.set('Authorization','Authorization object')
.set('Accept','application/json')
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.