【问题标题】:Angular 8 HttpClient Post Request Content-Type debacleAngular 8 HttpClient 发布请求内容类型崩溃
【发布时间】:2019-10-06 04:07:06
【问题描述】:

我不确定交易是什么,希望有人能给我一些帮助!

我正在尝试对后端 API 进行 POST,但我收到了 415 状态代码,因为内容类型正在作为“文本/纯文本”发送,但此端点需要应用程序/json。我想可能是 API,但 POST 在 PostMan 中工作得很好(见下面的截图)。

我尝试在请求标头中手动将 content-type 设置为 application/json,但我只得到 500 状态代码(见下面的屏幕截图)。 API 的所有其他端点都工作得很好,但他们期待“文本/纯文本”......非常感谢任何帮助!

我只是设置了一个简单的按钮来进行 POST:

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.less']
})
export class HomeComponent implements OnInit {

constructor(private http: HttpClient) { }

ngOnInit() {}

onClickMe( ) {

    // I'VE TRIED ALL THESE DIFFERENT WAYS ALSO

      /* 
        const headers = new HttpHeaders({
            'Content-Type': 'application/json'
        });

        const httpHeaders = new HttpHeaders();
        httpHeaders.append('Content-Type', 'application/json');

        const options = {
            headers: httpHeaders
        }; 
      */

    const httpHeaders = new HttpHeaders().set(
        'Content-Type',
        'application/json'
    );
    const uNameObj = {
        username: "asdf"
    };

    const jsonStr = JSON.stringify(uNameObj);
    let existsCheck: boolean;
    this.http
      .post('http://localhost:8080/myapp/user/username',
            '{"username": "asdf"}',
           {
             observe: 'response',
             headers: httpHeaders
            })
       .subscribe(
           responseData => {
               if (responseData.status === 200) {
                   existsCheck = true;
               } else {
                   existsCheck = false;
               }
           },
           error => {
               console.log('Error with post button', existsCheck);
           }
       );
    }
 }

【问题讨论】:

  • 您尝试过:this.http.post('http://localhost:8080/myapp/user/username', jsonStr, 以及您的 Post Action Method 的样子吗?
  • 是的,我试过了。抱歉,我的意思是说。
  • angular.io/guide/http#making-a-post-request 使用接口并发布uNameObj
  • 嘿安德鲁,我不太确定你的建议是什么

标签: angular post httpclient content-type angular8


【解决方案1】:

首先,对于您的具体情况,您实际上不需要做任何额外的事情来将请求Content-Type 设置为application/json。这就是 HttpClient 为您开箱即用的东西 for most of the cases

现在就您的错误而言,这与 CORS 有关。由于这是一个 AJAX 请求,当您的前端应用程序在单独的端口(最有可能是 4200)上运行时,您正在为一个在单独的端口(8080)上运行的 API 发出,浏览器会阻止该请求。

为了允许,它需要在响应标头中使用access-control-allow-origin: *。这是您的浏览器通过首先向 API 发送 OPTIONS 调用来执行的操作。

由于 API 在响应标头中实际上并没有 access-control-allow-origin: *,因此它将被阻止。这正是这里发生的事情。

修复:

由于这是一个 POST API,并且您在本地运行服务器,因此可以安全地假设您可以配置 REST API 服务器以启用 CORS。

如果它是 Express 服务器,您可以使用 cors 中间件在其上启用 CORS。

这里有一个Frontend - Sample StackBlitz 供您参考。

这里有一个Backend - CodeSandbox Sample 供您参考。

【讨论】:

  • 嗨@siddAjmera 这是事情的一部分,CORS 很好。 PostMan 请求顺利通过,我可以访问设置为 text/plain 的不同端点,只是这个和另一个设置为 application/json 的端点有问题。如果您查看第一个错误屏幕截图,它似乎是内容类型的文本/纯文本
  • API 是一个使用 Grizzly 后端的 Java。
  • 我添加了一个额外的屏幕截图,显示 API 中的 CORS
  • @NoobCoderChick Postman 是开发工具,因此不会触发您在后端可能遇到的任何 cors 问题。你没有得到 text/plain 错误的事实指向 cors,因为这种类型没有被 cors 覆盖。阅读this
  • @SiddAjmera 我接受了你的回答,因为它基本上是正确的回答。我想我会让你知道我如何解决它,以防你关心哈哈。我不知道为什么,但是当我发送 JSON 对象时,我的 API(Java/Jersey2)正在做一些时髦的事情。所以我现在从客户端发送一个 json 字符串,让我的 API 使用该字符串并将其转换为我可以使用的 json 对象。我仍然不确定为什么 Postman 会允许它工作,但是浏览器的某些问题导致了 preflight cors 错误....无论如何,非常感谢您的帮助!!!
猜你喜欢
  • 1970-01-01
  • 2016-04-08
  • 1970-01-01
  • 2017-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-25
  • 2016-09-04
相关资源
最近更新 更多