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

How to make a GET and POST request to an external API?

本文关键字:GET POST 请求 发出 API 外部      更新时间:2023-09-26
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);
        }
    });
});
}

这是api代码,我需要使GET和POST请求。但是我不知道怎么做。

看起来你的代码正在使用express,这通常对你的应用程序的构建和API很好。然而,要向第三方API发出一个简单的请求,并留在node.js中,为什么不尝试请求模块呢?https://www.npmjs.org/package/request

你的例子没有显示请求的路径是什么,或者你是否需要任何额外的头等,但这里是一个使用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
});