angular中的http服务将发布数据作为请求主体的密钥发送,没有任何值

时间:2016-04-20 16:39:57

标签: javascript angularjs node.js api express

我正在构建一个角度应用程序,我正在使用$ http服务。当我向我的节点api发送一个帖子请求时,我的帖子数据显示为req.body的键,其中一个空字符串作为值。

在我的服务器端登录我的req.body和req.headers我得到了这个

{ '{"username":"niccolo","password":"pass123"}': '' } //req.body
{ host: 'localhost:3000',
  connection: 'keep-alive',
  'content-length': '43',
  accept: '*/*',
  origin: 'http://localhost:3000',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36',
  'content-type': 'application/x-www-form-urlencoded',
  referer: 'http://localhost:3000/login',
  'accept-encoding': 'gzip, deflate',
  'accept-language': 'en-US,en;q=0.8' } //req.header

以下是发出请求的服务

angular.module('dochub.services').service('Auth', ['$http', '$rootScope',function($http, $rootScope){
  this.login = function(user, cb){
    config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': '*/*'
      }
    }
    req = $http.post($rootScope.apiBaseUrl+'users/login', user, config);
    req.success(function(data){
      cb(data);
    })
  }
  this.logout = function(cb){
    cb(data);
  }
}]);

当我使用PostMan向该端点发出请求时,它工作正常,所以我猜问题必须与我的角度代码一起

2 个答案:

答案 0 :(得分:2)

从角色

更改内容类型标题
'Content-Type': 'application/x-www-form-urlencoded'

'Content-Type': 'application/json'

那应该解决它。

答案 1 :(得分:1)

如果你正在使用带有快递的身体解析器

试试这个

var express = require('express');
var app = express();
var parser = require('body-parser');

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

app.use(parser.json());

您可以使用默认的Content-Type和$ http

'Content-Type: application/json'