[英]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.