How to send a message using http from @ angular / http

I use the following code to send a send 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 get the 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 related concepts.

+3
javascript post angular
Nov 02 '17 at 18:45
source share
2 answers

You are mixing classes: HttpHeaders comes with HttpClient , which replaces Http with 4.3.

Other 403 comments are worth exploring, but at least do the following:

 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); } } 

Please note that you can use the destruction destination in the body of the message (when the name of your object matches the name of the variable you are replacing it with).

+1
Nov 02 '17 at 19:11
source

My problem was due to CORS. Despite the fact that I turned on the CORS chrome plugin, still because I specified the parameters, the response to the pre-flight request was sent to the server, which was rejected

The solution that helped was to add the CORS annotation to my rest controller in Java, so maybe only server side code can help here.

 @CrossOrigin(origins = "*") <------ this solved the issue of post request getting failed @RestController public class ProductController {... 
0
Nov 02 '17 at 20:27
source



All Articles