Make a GET request to JSON API in Node.js?

后端 未结 3 1398
一个人的身影
一个人的身影 2021-02-04 14:42

Wondering how I can make a GET request to a JSON API using Node.js. I preferably want to use Express however it is not necessary, and for the output to be on a Jade page. I\'m s

3条回答
  •  忘掉有多难
    2021-02-04 15:09

    var request = require('request');
    request('', function (error, response, body) {
        if (!error && response.statusCode == 200) {
          var info = JSON.parse(body)
        }
    })
    

    This will make an HTTP request to the API and upon success parse the response into JSON.

    As far as getting the response onto a Jade page do you wish to do an API call (to your own server) and then use AngularJS/ jQuery/ another framework to fill in the information?

    If you wish to add this to your own route consider embedding it like such:

    var express = require('express');
    var cors = require('cors');
    var request = require('request');
    var app = express();
    app.use(express.bodyParser());
    app.use(cors());
    app.get('', function(req, res){
      request('', function (error, response, body) {
        if (!error && response.statusCode == 200) {
          var info = JSON.parse(body)
          // do more stuff
          res.send(info);
        }
      })
    });
    app.listen(3000);
    console.log("The server is now running on port 3000.");
    

提交回复
热议问题