【问题标题】:POSTing data from angularJS to Express using $http使用 $http 将数据从 angularJS 发布到 Express
【发布时间】:2017-08-22 22:50:47
【问题描述】:

我正在尝试将一些 json 数据从 angularjs 发送到 express/nodejs

AngularJS 代码:

$http({
      method: 'POST',
      url: 'http://localhost:8000/api/auth',
      data: {
         name: user,
         password: passwd
      },
      headers: {
         'Content-Type': 'application/x-www-form-urlencoded'
      }
   })
   .success(function(data, status, headers, config) {
      $scope.loginStatus = data;
   })
   .error(function(data, status, headers, config) {
      $scope.lloginStatusogin = data;
   });

ExpressJS 代码:

var express = require('express');
var app = express();


var config = require('./config'); // get our config file


var port = process.env.PORT || 8000; // used to create, sign, and verify tokens

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
   extended: true
}));

app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});

var apiRoutes = express.Router();

apiRoutes.post('/auth', function(req, res) {

   console.log(req.body)
});

app.use('/api', apiRoutes);
app.listen(port);

但是在快速记录req.body 时,我得到了这个对象 { '{"name":"Nick","password":"password"}': '' },整个 json 对象被视为具有空值的属性,我不明白或看不出做错了什么。

【问题讨论】:

  • 尝试将标题'Content-Type': 'application/x-www-form-urlencoded'改为'Content-Type: application/json'
  • Xsmael 有什么反馈或建议吗?
  • @Dario ir 没有提到它,但我也试过了,但没有用
  • @lin 对不起,我离线了...
  • 没问题 m8 =)

标签: angularjs json node.js api express


【解决方案1】:

如果您尝试发送对象,请发送Content-Type: application/jsonapplication/x-www-form-urlencoded 需要一个 urlEncoded 字符串作为正文属性。以下两种解决方案都适合您,请选择一个。

使用application/json content-type 将 JSON 对象作为正文发送

$http({
    method  : 'POST',
    url     : 'http://localhost:8000/api/auth',
    data    : {
        name: user,
        password: passwd
    },
    headers : {'Content-Type': 'application/json'}
})
.success(function(data, status, headers, config){
    $scope.loginStatus=data;
})
.error(function(data, status, headers, config){
    $scope.lloginStatusogin=data;
});

 


在正文中发送带有application/x-www-form-urlencoded content-type 的urlEncoded sring。

transformRequest 将在发送请求之前基于data 创建一个 urlEncoded 字符串。

$http({
    method: 'POST',
    url: 'http://localhost:8000/api/auth',    
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
        return str.join("&");
    },
    data: {
        name: user,
        password: passwd
    },
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data, status, headers, config){
    $scope.loginStatus=data;
})
.error(function(data, status, headers, config){
    $scope.lloginStatusogin=data;
});

【讨论】:

  • $.param 使用 jQuery 吗?
  • 哦,是的,等等,我通过转换数据为 angularjs 添加了正确的方法。
  • 你是怎么知道transformRequest的?我从没见过,帅哥!
  • 做得好,x-www-form-urlencoded 早在 AngularJS 创建之前就已经是一些网络标准了。通过这种方式,很容易知道该请求需要什么样的主体。 =) 几年前我在 AngularJS 中遇到过这个“问题”。很高兴为您提供帮助
  • 是的,经验很重要,谢谢我在这个问题上浪费了一整天 :((但它可能会更糟:))
【解决方案2】:

在标题部分:应该是

{'Content-Type': 'application/json'} 

而不是

{'Content-Type': 'application/x-www-form-urlencoded'}

【讨论】:

    猜你喜欢
    • 2015-11-25
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2012-12-06
    • 2018-02-06
    • 2019-04-25
    相关资源
    最近更新 更多