【问题标题】:How to make a GET and POST request to an external API?如何向外部 API 发出 GET 和 POST 请求?
【发布时间】:2014-06-22 07:54:41
【问题描述】:
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 代码。但我不知道该怎么做。

【问题讨论】:

    标签: javascript api express


    【解决方案1】:

    您的代码似乎正在使用 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
    });
    

    【讨论】:

    • 有什么方法可以通过使用 (xmlhttprequest) 的 ajax 来实现。谢谢
    猜你喜欢
    • 2017-05-24
    • 2021-07-10
    • 2019-07-07
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    相关资源
    最近更新 更多