简体   繁体   中英

Angular 8 HttpClient Post Request Content-Type debacle

I'm not sure what the deal is, hopefully someone can give me some help!

I'm trying to make a POST to the backend API, but I get a 415 status code because the content-type is being sent as "text/plain" but this endpoint is expecting application/json. I thought maybe it was the API, but the POST works just fine in PostMan (see screenshot below).

I've tried to manually set the content-type to application/json in the request headers, but I just get a 500 status code (see screenshot below). All other endpoints of the API are working just fine, but they're expecting "text/plain"...any help is greatly appreciated!

I just setup a simple button to make the 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 过滤器

First of all, for your specific case, you don't really need to do anything extra to set the request Content-Type as application/json . That's something that HttpClient does for you out of the box for most of the cases .

Now as far as your error is concerned, that has something to do with CORS. Since this is an AJAX Request you're making for an API running on a separate PORT(8080) while your Frontend Application is running on a separate port(4200 most probably), the browser would block the request.

To allow, it would need access-control-allow-origin: * in the response headers. This is something that your browser would do by sending an OPTIONS call to the API first.

Since the API doesn't really have access-control-allow-origin: * in the response header, it would be blocked. That's exactly what's happening here.

FIX:

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.

If it were an express server you could enable CORS on it using thecors middleware.

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

Here's aBackend - CodeSandbox Sample for your ref.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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