Angular 8 HttpClient Post 请求 Content-Type 崩溃

Angular 8 HttpClient Post Request Content-Type debacle

不知道是什么情况,希望有人能帮帮我!

我正在尝试将 POST 发送到后端 API,但我收到 415 状态代码,因为 content-type 正在作为 "text/plain" 发送,但是此端点需要 application/json。我想也许是 API,但 POST 在 PostMan 中工作得很好(见下面的截图)。

我试图在请求 headers 中手动将 content-type 设置为 application/json,但我只得到一个 500 状态代码(见下面的屏幕截图)。 API 的所有其他端点工作正常,但他们期待 "text/plain"...非常感谢任何帮助!

我只是设置了一个简单的按钮来制作 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);
           }
       );
    }
 }

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

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

要允许,它需要在响应 header 中包含 access-control-allow-origin: *。这是您的浏览器通过首先向 API 发送 OPTIONS 调用来完成的事情。

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

修复:

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

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

Here's a Frontend - Sample StackBlitz for your ref.

Here's a Backend - CodeSandbox Sample for your ref.