简体   繁体   English

使Ajax调用Angular到Node.js(express.js)

[英]Making Ajax call Angular to Node.js (express.js)

I am trying simple thing. 我正在尝试简单的事情。 Make ajax call to node express and do something based on it. 对node express进行ajax调用并根据它执行某些操作。 I am not being able to access req.body, I mean it is empty when debuggin from node.js side 我无法访问req.body,我的意思是当从node.js端调试时它是空的

NODE SIDE. NODE SIDE。 I am using: 我在用:

app.use(express.bodyParser());

and this is mine test method in express: 这是快递中的矿山测试方法:

app.get('/courses', function(request, response) {
  console.log("I have been hit"); //I Am getting here               
});

ANGULAR SIDE: 角砾侧:

eventsApp.factory('MainConnector', function($http, $q, $resource ) {
  return {
    mainConnection: function( ) {

      var requestBody = {
        id: 3,
        name: 'testname',
        lastname: 'testlastname'
      }

      $http.get("http://localhost:3000/courses", requestBody)
        .success(function(data, status, headers, config) {
          console.log("this is coming from wherever:" + data);
          $scope.data = data;
        }).error(function(data, status, headers, config) {
          $scope.status = status;
        });
    }      
  };
});

I am trying access (from node side) 我正在尝试访问(从节点端)

req.body.name

But body is always empty, as if I am not sending anything. 但身体总是空的,好像我没有发送任何东西。

Your ExpressJS test handler is not actually responding with any data, which is why you get an empty body back. 你的ExpressJS测试处理程序实际上没有响应任何数据,这就是为什么你得到一个空体。 Check out the expressjs site for documentation . 查看expressjs网站以获取文档

Basically you want something like this 基本上你想要这样的东西

app.get('/courses', function(request, response) {
  console.log("I have been hit"); //I Am getting here
  response.send('hello world');            
});

Secondly you are trying to send data with your get request. 其次,您正尝试使用get请求发送数据。 If you take a look at the angularjs documentation you will see that $http.get only takes 1 parameter, the url. 如果您查看angularjs文档,您将看到$http.get只接受1个参数,即url。

This means the AngularJS factory you want is more like this: 这意味着你想要的AngularJS工厂更像是这样的:

eventsApp.factory('MainConnector', function($http, $q, $resource ) {
  return {
    mainConnection: function( ) 
      $http.get("http://localhost:3000/courses")
        .success(function(data) {
          console.log("this is coming from wherever:" + data);
        });
    }      
  };
});

But lets say you did want to send something to the server, what you want is a POST request. 但是,假设您确实想要向服务器发送内容,您想要的是POST请求。 This means you update your express handler to respond to POST instead of GET. 这意味着您更新快递处理程序以响应POST而不是GET。

app.get('/courses', function(request, response) {
  response.send(request.body);            
});

This is a simple "echo" handler. 这是一个简单的“echo”处理程序。 It will just send back to the client whatever the client sent to it. 无论客户端发送给客户端,它都会发送回客户端。 If you send it "Hello" it will respond "Hello". 如果你发送“Hello”,它将回复“你好”。

And a corresponding AngularJS service factory 和相应的AngularJS服务工厂

eventsApp.factory('MainConnector', function($http, $q, $resource ) {
  return {
    mainConnection: function( )
      var data = {name: "hello"};
      $http.post("http://localhost:3000/courses", data)
        .success(function(data) {
          console.log("this is coming from wherever:" + data);
        });
    }      
  };
});

As it turns out to be, this was two problems. 事实证明,这是两个问题。 Yes, there was this issue using GET and sending payload. 是的,使用GET和发送有效负载存在此问题。 However, that did not fix the problem. 但是,这并没有解决问题。 Problem was in CORS. 问题出在CORS中。 This is how I fixed it: 这就是我修复它的方法:

var allowCrossDomain = function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'content-type, Authorization, Content-Length, X-Requested-With, Origin, Accept');

    if ('OPTIONS' === req.method) {
        res.send(200);
    } else {
        next();
    }
};

and

app.configure(function () {
    app.set('port', process.env.PORT || 3000);
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(allowCrossDomain);
    app.use(app.router);   
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM