I am using following code to send a post request
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);
}
}
however I am getting following error in 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'.
Please help clarify associated concepts
You are mixing classes: HttpHeaders
goes with HttpClient
, which replaces Http
since 4.3.
The other comments about 403 are worth investigating, but at a minimum, do this:
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);
}
}
Note that you can use a destructuring assignment in the post body (when your object key name is the same as the variable name you are replacing it with).
My problem was due to CORS, Even though I have enabled CORS chrome plugin, still because I was specifying options, a preflight response was send to server which was rejected
The solution which helped was putting CORS annotation on my rest controller in Java, so probably only server side code can help here
@CrossOrigin(origins = "*") <------ this solved the issue of post request getting failed
@RestController
public class ProductController {...