繁体   English   中英

Angular 8 HttpClient 发布请求内容类型崩溃

[英]Angular 8 HttpClient Post Request Content-Type debacle

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

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

我尝试在请求标头中手动将内容类型设置为 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);
           }
       );
    }
 }

没有添加标题选项 在标题中更改了 CONTENT_TYPE

邮递员屏幕截图 - 200 状态代码: 后端 API CORS 过滤器

首先,对于您的特定情况,您实际上不需要做任何额外的事情来将请求Content-Type设置为application/json 在大多数情况下,这是HttpClient开箱即用为您所做的事情。

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

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

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

使固定:

Since this is a POST API and you're running the server on the local, it's safe to assume that you can configure the REST API server to enable CORS.

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

这是一个前端 - 供您参考的 StackBlitz 示例

这是您的参考的后端 - CodeSandbox 示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM