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

标签 ajax node.js angularjs

我正在尝试简单的事情。对 node express 进行 ajax 调用并基于它做一些事情。我无法访问 req.body,我的意思是当从 node.js 端调试时它是空的

Node 端。 我正在使用:

app.use(express.bodyParser());

这是我在 express 中的测试方法:

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

Angular 边:

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;
        });
    }      
  };
});

我正在尝试访问(从 Node 端)

req.body.name

但是 body 总是空的,好像我什么都没发送。

最佳答案

您的 ExpressJS 测试处理程序实际上并未响应任何数据,这就是您返回空主体的原因。查看expressjs site for documentation .

基本上你想要这样的东西

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

其次,您正尝试通过获取请求发送数据。如果您看一下 angularjs 文档,您会发现 $http.get 只需要 1 个参数,即 url。

这意味着你想要的 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);
        });
    }      
  };
});

但是假设你确实想向服务器发送一些东西,你想要的是一个 POST 请求。这意味着您更新您的 express 处理程序以响应 POST 而不是 GET。

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

这是一个简单的“回声”处理程序。它只会将客户端发送给它的任何内容发回给客户端。如果您向它发送“Hello”,它会回复“Hello”。

以及相应的 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);
        });
    }      
  };
});

关于ajax - 使 Ajax 调用 Angular 到 Node.js (express.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19687667/

相关文章:

javascript - 在 Rails 上使用 angularjs 和 ruby​​ 时出现未知的 Provider e-provider 错误

javascript - 如何在AngularJS中调整图像大小?

javascript - jquery.form 和跨域请求

java - 使用 Jackson 使用 @RequestBody 进行 ajax 发布时出现 400 错误请求

javascript - 尝试从 node.js 向 Django 发出 POST 请求

node.js - 大文件的事件循环?

javascript - 在 JavaScript 中比较对象数组中对象的属性

java - 如何使用Ajax进行jquery表单提交?

javascript - 有没有办法在使用 AJAX 的父级之前在 div 中加载隐藏的 div?

AngularJS $http.post 请求被 Chrome 取消