如何向外部API发出GET和POST请求?

时间:2014-06-22 07:54:42

标签: javascript api express

var Attendance = require('../../../collections/attendance').Attendance;

var moment = require('moment');

module.exports = function(app) {

app.get('/api/trackmyclass/attendance', function(req, res) {
    var data = req.body;
    data['user'] = req.user;
    Attendance.getByUser(data, function(err, d) {
        if (err) {
            console.log('This is the err' + err.message);
            res.json(err, 400);
        } else {
            var job = d['attendance'];
            if (typeof job != undefined) {
                res.json(job);
                console.log('This is it' + job['status']);
            } else
                res.json('No data Present', 200);
        }

    });
});

app.post('/api/trackmyclass/attendance', function(req, res) {
    var data = req.body;
    data['user'] = req.user;
    Attendance.create(data, function(err, d) {
        if (err) {
            console.log('This is the err' + err.message);
            res.json(err, 400);
        } else {
            var attendance = d['attendance'];
            if (typeof job != undefined) {
                console.log('Attendance record created' + attendance);
                res.json(attendance);
            } else
                res.json('No data Present', 200);
        }

    });
});
}

这是我需要进行GET和POST请求的api代码。但我不知道该怎么做。

1 个答案:

答案 0 :(得分:3)

您的代码看起来像是使用express,这通常适合您的应用的构建和API。但是,为了向第三方api发出一个简单的请求并留在node.js中,为什么不尝试一下这个很棒的请求模块。 https://www.npmjs.org/package/request

您的示例未显示请求的路径是什么,或者您是否需要任何附加标头等,但这是使用请求的GET请求的简单示例。

var request = require('request');

function makeCall (callback) {
    // here we make a call using request module
    request.get( 
        { uri: 'THEPATHAND ENDPOINT YOU REQUEST,
         json: true,
          headers: {
            'Content-Type' : 'application/x-www-form-urlencoded',
        }
        },
        function (error, res, object) {
          if (error) { return callback(error); }

            if (res.statusCode != 200 ) {
              return callback('statusCode');
            }

            callback(null, object);
        }
      );

}

或jquery .ajax从前端客户端指向您的路径

$.ajax({
url: "pathtoyourdata",
type: "GET",
})
.done(function (data) {
//stuff with your data
});