![](/img/trans.png)
[英]angular post request with content-type application/json not working
[英]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
設置為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。
這是您的參考的后端 - CodeSandbox 示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.