我正在处理angular 6项目,我想使用post方法发送请求。使用get方法可以正常工作,但是当我尝试使用post方法时,却收到类似Error
的错误我认为此问题与CORS有关,但我不知道如何解决。如果有人知道解决方案,请提供帮助。
home.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
console = console;
public form = {
};
id = 10;
public item:any[];
public item2:any[];
private url1 = `http://localhost/api.php?id=${this.id}`;
private url2 = `http://localhost/api.php`;
constructor(private http:HttpClient) { }
ngOnInit() {
return this.http.get(this.url1).subscribe( result=>{
this.item = result as caster[];
console.log(this.item);
});
}
/**
* onSubmit
*/
public onSubmit() {
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
return this.http.post(this.url2, {'id': 3}, httpOptions).subscribe( result=>{
this.item2 = result as caster[];
console.log(this.item2)
});
}
}
interface caster {
id: number;
name: string
age: number
}
home.component.html
<form #loginForm="ngForm" (ngSubmit)="onSubmit()">
<button type="submit">Save</button>
</form>