我正在使用以下代码发送帖子请求
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'.
请帮助澄清相关概念
答案 0 :(得分:1)
您正在混合课程:HttpHeaders
与HttpClient
一致,替换 Http
自4.3以来。
关于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);
}
}
请注意,您可以在帖子正文中使用destructuring assignment(当您的对象键名称与要替换它的变量名称相同时)。
答案 1 :(得分:0)
我的问题是由于CORS,即使我启用了CORS chrome插件,仍然是因为我指定了选项,预检响应被发送到被拒绝的服务器
帮助的解决方案是在Java中将CORS注释放在我的其余控制器上,所以可能只有服务器端代码可以在这里提供帮助
@CrossOrigin(origins = "*") <------ this solved the issue of post request getting failed
@RestController
public class ProductController {...