Angular8个httpclient如何发送JSONheader

Angular 8 httpclient how to send JSON header

我正在尝试使用 angular 8 HttpClient 将 JSON 发送到使用以下代码的 ASP.net 核心后端:

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

import { User } from '@/_models';

    login(username, password) {
        return this.http.post<any>(`https://${config.apiUrl}/api/User/LoginUser`,
                JSON.stringify({
                    "username": username,
                    "password": password 
                })
        ).pipe(map(user => {
            // store user details and jwt token in local storage to keep user logged in between page refreshes
            localStorage.setItem('currentUser', JSON.stringify(user));
            console.log(user);
            this.currentUserSubject.next(user);
            return user;
        }));
    }
}

但是,当尝试发送 JSON 登录到使用命令 npm start 托管的登录页面时,所以

localhost:8080/login

正在发送请求。

请求headers是:

POST /api/User/LoginUser HTTP/1.1
Host: (Checked_and_correct_API_URL)
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:71.0) Gecko/20100101 Firefox/71.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: http://localhost:8080/login
Content-Type: text/plain
Content-Length: 49
Origin: http://localhost:8080
DNT: 1
Connection: keep-alive

响应headers是:

HTTP/2.0 415 Unsupported Media Type
content-type: application/problem+json; charset=utf-8
server: Microsoft-IIS/10.0
x-powered-by: ASP.NET
date: Thu, 19 Dec 2019 13:10:01 GMT
content-length: 147
X-Firefox-Spdy: h2

发送的参数为:

{"username":"jeboimarc2","password":"KUTminor1!"}

这也是正确的

谁能告诉我为什么会出现不受支持的媒体类型错误?提前致谢。

传递原始 json 数据,不要将其转换为字符串。

这样试试:

return this.http.post<any>(`https://${config.apiUrl}/api/User/LoginUser`,{"username": username, "password": password })