无法向 MEAN JS 中的外部 API 发送 http/https 请求

cannot send an http/https request to an external API in MEAN JS

我正在 MEAN JS 上开发应用程序。我是 MEAN JS 的新手。
我想访问外部 API 以获得 json 响应,如下所示 -
{"id":"7gd6ud7ud5r0c","name":"jack","zip":"94109","gender":"Male"}

我有这个参考 here (https://nodejs.org/api/https.html)..
但我不知道如何在客户端控制器中使用 http/https 请求。

这是我的express.js

'use strict';

/**
 * Module dependencies.
 */
var fs = require('fs'),
http = require('http'),     // required already
https = require('https'),   // required already
express = require('express'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
.....
.....
.....

这是我的invite.client.controller.js

    'use strict';
    angular.module('core').controller('InviteController', ['$scope', 
    'Authentication', '$http',
        function($scope, Authentication, $http) {
        // This provides Authentication context.
        $scope.authentication = Authentication;

     $scope.getMembersFromAPI = function(){

            ***************************************
            // this block shows error ReferenceError: require is not defined
            var http = require('http'),  
                https = require('https');
            ***************************************
            var options = {
              hostname: 'https://api.somedemodp.com/v5/td?api_key=ec96c9afcbb6bbb8f5a687bd7&email=vlad@rapleafdemo.com',
              path: '/',
              method: 'GET'
            };

            var req = https.request(options, function(res) {
              console.log('statusCode: ', res.statusCode);
              console.log('headers: ', res.headers);

              res.on('data', function(d) {
                process.stdout.write(d);
              });
            });
            req.end();

            req.on('error', function(e) {
              console.error(e);
            });

        };
    }
]);

...您是否混淆了 angular 和 express 代码?您没有在 angular 中使用 require。你使用依赖注入。

Angular是前端,express是后端。它们是解耦的。

angular.module('core').controller('InviteController', ['$scope', 
'Authentication', '$http',
    function($scope, Authentication, $http) 

这是你做依赖注入的地方(类似于node/express中的require)你已经注入了$http.

实际上,您可以使用 $http 调用直接从 angular 内部调用外部 API - 来自文档:

// Simple GET request example :
$http.get('/someUrl').
 success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

https://docs.angularjs.org/api/ng/service/$http

对于那些运行进入这个问题的人。我建议阅读此博客:calling third party web api's from the mean stack

您遇到的问题是由于浏览器阻止了 cross-domain 调用。方法是从服务器联系 API 并将其发送到前端。

注意:我自己还没有尝试过,但是,显然通过在接收端启用 CORS + 发送正确的 headers 将允许你做跨域来自前端的调用。