Angular 中的 HTTP 服务将 POST 数据作为请求正文的键发送,没有值

http service in angular sends post data as the key of the request body with no value

本文关键字:正文 请求 服务 HTTP 中的 POST 数据 Angular      更新时间:2023-09-26

我正在构建一个角度应用程序,我正在使用$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 向该端点发出请求时,它工作正常,所以我想问题必须出在我的角度代码上

将 Content-Type 标头从

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

'Content-Type': 'application/json'

这应该可以解决它。

如果您将正文解析器与 express 一起使用

试试这个

var express = require('express');
var app = express();
var parser = require('body-parser');
app.use(parser.urlencoded({
  extended: true
}));
app.use(parser.json());

您可以将默认的内容类型与$http

'Content-Type: application/json'