我不确定这是什么交易,希望有人能给我一些帮助!
我正在尝试对后端API进行POST,但由于内容类型以“文本/纯文本”形式发送,但该端点需要application / json,所以我得到了415状态代码。我以为可能是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请求,因此您要使API在单独的PORT(8080)上运行,而前端应用程序在一个单独的端口(最有可能是4200)上运行,因此浏览器将阻止该请求。
为了允许,响应头中需要access-control-allow-origin: *
。您的浏览器可以通过首先向API发送OPTIONS
调用来完成此操作。
由于API在响应标头中实际上没有access-control-allow-origin: *
,因此将被阻止。这就是这里正在发生的事情。
由于这是POST API,并且您正在本地运行服务器,因此可以安全地假设您可以配置REST API服务器以启用CORS。
如果是快速服务器,则可以使用cors
中间件在其上启用CORS。
这里是
cors
供您参考。这里是Frontend - Sample StackBlitz供您参考。