[英]how to send post request using http from @angular/http
我正在使用以下代碼發送帖子請求
import { Http, Headers, Response } from '@angular/http'; @Injectable() export class AuthenticationService { private _options = new Headers({'Content-Type': 'application/json'}); constructor(private http: Http) { } login(username: string, password: string) { return this.http.post('http://localhost:56451/map', { "username": username, "password": password }, this._options); } }
但是我在vscode中遇到以下錯誤
Argument of type '{ headers: HttpHeaders; }' is not assignable to parameter of type 'RequestOptionsArgs'. Types
of property 'headers' are incompatible. Type 'HttpHeaders' is not assignable to type 'Headers'. Property 'forEach'
is missing in type 'HttpHeaders'.
請幫助澄清相關概念
你正在混合類: HttpHeaders
配備HttpClient
,它取代了自4.3以來的Http
。
關於403的其他評論值得研究,但至少要做到這一點:
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
@Injectable()
export class AuthenticationService {
private _options = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
// Inject HttpClient, not Http
constructor(private http: HttpClient) { }
login(username: string, password: string) {
return this.http.post('http://localhost:56451/map',
{ username, password },
this._options);
}
}
請注意,您可以在帖子正文中使用解構分配 (當您的對象鍵名稱與要替換它的變量名稱相同時)。
我的問題是由於CORS,即使我已經啟用了CORS chrome插件,仍然因為我指定了選項,預檢響應被發送到服務器被拒絕
幫助的解決方案是在Java中將CORS注釋放在我的其余控制器上,因此可能只有服務器端代碼可以在這里提供幫助
@CrossOrigin(origins = "*") <------ this solved the issue of post request getting failed
@RestController
public class ProductController {...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.