web-dev-qa-db-ja.com

Node.jsの中でremote RESTを呼び出すにはどうすればいいですか?どんなCURL?

Node.jsでは、子プロセスを使用してCURLを呼び出す以外に、CURL呼び出しを行う方法があります。リモートサーバーRESTAPIと戻りデータを取得しますか?

また、リクエストヘッダーをremoteREST呼び出しに設定し、さらにGET(またはPOST)で文字列をクエリする必要があります。

私はこれを見つける: http://blog.nodejitsu.com/jsdom-jquery-in-5-lines-on-nodejs

しかし、それはPOSTクエリ文字列への道を示しません。

171
murvinlai

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();
202
Raynos

Request - 簡易HTTPクライアント の使い方はどうですか.

これがGETです:

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もPOSTを望んでいました:

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

http://isolaso​​ftware.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);
});
34
Giulio Roggero

私は node-fetch を使っています。なぜならそれはおなじみの(あなたがWeb開発者なら) fetch()API を使うからです。 fetch()はブラウザから任意のHTTPリクエストを行うための新しい方法です。

はい、これはノードjsの質問ですが、暗記して理解しなければならないAPIの開発者の数を減らし、JavaScriptコードの再利用性を向上させたいのではありませんか。 フェッチは標準 なので、それについてはどうですか。

Fetch()に関するもう1つのいいところは、javascript Promise を返すことです。そのため、次のような非同期コードを書くことができます。

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);});

取って代わる XMLHTTPRequest 。これが 詳細な情報 です。

28
saille

私はWebサービスを呼び出すために レスラー を使ってきました。

11
swapnil_mishra

もう一つの例 - そのためにリクエストモジュールをインストールする必要があります

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

最新のAsync/Await機能を使用する

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

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

//コード

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
codemirror

CURLでは見つけられなかったので、 node-libcurl のラッパーを書き、 httpsにあります://www.npmjs.com/package/vps-rest-client .

POSTを作るのはこんな感じです:

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));
3
Jonatas Walker

アクシオ

Node.jsでAxiosを使用した例(axios_example.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);

あなたのプロジェクトディレクトリであなたがすることを確認してください:

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

ブラウザを使ってNode.js REST AP​​Iをテストすることができます:http://localhost:5000/search?queryStr=xxxxxxxxx

同様にあなたは投稿をすることができます:

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

スーパーエージェント

同様にSuperAgentを使うことができます。

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

そして、あなたが基本認証をしたいならば:

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));
});

参照:

3
Yuci
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
Seb

Node.js 4.4以降をお持ちの場合は、 reqclient を参照してください。呼び出しを行い、要求をcURLに記録できます。 スタイルなので、アプリケーションの外部で呼び出しを簡単に確認して再現できます。

単純なコールバックを渡す代わりに Promise オブジェクトを返すので、結果をより「ファッション」の方法で処理できます。 、 チェーン 簡単に結果を表示し、標準的な方法でエラーを処理します。また、ベースURL、タイムアウト、コンテンツタイプの形式、デフォルトのヘッダー、URL内のパラメータとクエリのバインド、基本的なキャッシュ機能など、リクエストごとに定型的な設定を多数削除します。

これは、それを初期化し、呼び出しを行い、curlスタイルで操作を記録する方法の例です。

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"});

これでコンソールにログインします。

[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

そして応答が返されると...

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

これは、promiseオブジェクトを使用して応答を処理する方法の例です。

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

npm install reqclientと一緒にインストールすることもできます。

2
Mariano Ruiz

curlrequest を使用して、要求する時間を簡単に設定できます。オプションのヘッダーにも "を設定できます。 )偽の "ブラウザ呼び出し。

1
luizpanariello

あなたがform-dataを使って実装するならば、より多くの情報( 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
Lwf804