【问题标题】:Angular 7 not sending HTTP Post request dataAngular 7 不发送 HTTP Post 请求数据
【发布时间】:2019-09-15 08:21:45
【问题描述】:

我正在尝试向使用 ExpressJS 开发的 REST API 发送 HTTP Post 请求。我正在使用 Angular 的 HttpClient 使用以下服务文件来发送请求:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOiJ0ZXN0MiIsImxldmVsIjoxLCJpYXQiOjE1NTYyMDU0OTMsImV4cCI6MTU1NjI5MTg5M30.luqbDb-sSLxsX0LKFTaF6NTYDO4tS6kCI8V_d9pizmA'
    })
};

@Injectable({
  providedIn: 'root'
})
export class ApiserviceService {

  constructor(private http: HttpClient) { }

  getData(url: string) {
    return this.http.get(url)
  }
  postData(url: string, data: Object) {
    console.log(data);
    return this.http.post(url, data, httpOptions)
  }
}

使用以下代码调用服务:

/* other Component class code */
constructor(private data: ApiserviceService) {}

submit()
{
let url: string =
    "http://xxx.xxx/api/hotels/"
    + this.route.snapshot.params.hotelId
    + "/reviews";
    this.data.postData(url, this.revForm.value).subscribe(data => {
      console.log(data);
      this.router.navigate(['/']);
    });
}

我必须添加一个授权标头,因为 API 将拒绝所有不携带令牌的请求。

在服务文件中 http.post 语句正上方的控制台日志中,我得到了完全符合要求的数据,一个带有所有必需参数的 JSON 对象被打印在 Google Chrome 的控制台上。但是,由于某种原因,Angular 应用正在发送一个空请求。

我在响应中收到了缺失值错误,因此为了找出原因,我在 API 控制器中添加了以下行以及错误处理:

console.log(req.body);

这是来自 API 的函数:

var _addReview = function(req, res, data) {
        data.reviews.push({
                name : req.body.name,
                rating : parseInt(req.body.rating, 10),
                review : req.body.review,
                id : req.userid
        });
        data.save(function(err, hotelUpdated){
                if(err) {
                        console.log(req.body);
                        res.status(500).json(err);
                }
                else {
                        res.status(201).json(hotelUpdated.reviews[hotelUpdated.reviews.length - 1]);
                }
        });
};

NodeJS 的控制台打印了一个空对象 {}。我尝试将 Content-Type 更改为 application/json 但仍然没有运气。

我还在 NodeJS 控制台中注意到,我的 Angular 应用程序在 POST 请求之前发送了一个 OPTIONS 请求。我上网查了一下,发现只有在OPTIONS请求返回200码后才会发送POST请求。但是我的 POST 请求正在发送,因为我收到了响应。所以我相信 OPTIONS 请求会成功。

我的 API 在 Postman 中运行良好,即使我发送的标头与在 Angular 应用程序中完全相同。

【问题讨论】:

    标签: angular httprequest


    【解决方案1】:

    对于CORSOPTIONS 调用(只有标题,没有正文)需要是taken care of

    【讨论】:

      【解决方案2】:

      通过使用 Content-Type: application/json 而不是 application/x-www-form-urlencoded 发送请求来解决问题。显然 Angular 没有像 Postman 那样将 application/x-www-form-urlencoded 转换为 json-parseable 数据。

      【讨论】:

        【解决方案3】:

        你在路由处理中使用 body-parser 中间件吗?

        参见下面的示例:

        var express = require('express')
        var bodyParser = require('body-parser')
        
        var app = express()
        
        // parse application/x-www-form-urlencoded
        app.use(bodyParser.urlencoded({ extended: false }))
        
        // parse application/json
        app.use(bodyParser.json())
        
        app.use(function (req, res) {
          res.setHeader('Content-Type', 'text/plain')
          res.write('you posted:\n')
          res.end(JSON.stringify(req.body, null, 2))
        })
        

        【讨论】:

        • 是的,我已经在使用 bodyparser 中间件,并且在 postman 中一切似乎都运行良好。只是不接受来自 Angular 的数据
        猜你喜欢
        • 2018-08-04
        • 1970-01-01
        • 2013-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多