While I am trying to make post request in HttpClient
getting the below error while same with rest client giving proper response. Same with angular 1 $http
service is working as expected.
Tried multiple ways but neither post nor get method is working.
I am using angular-cli in which I have configured proxy.config.json
{
"/api/*":{
"target":"http://10.104.40.14:8290/my_app",
"secure":false,
"logLevel":"debug"
}
}
// error code
zone.js:2933 POST http://localhost:4200/api/security/login 401 (Unauthorized)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 401 Unauthorized</title>
</head>
<body><h2>HTTP ERROR 401</h2>
<p>Problem accessing /de_prp/error. Reason:
<pre> Unauthorized</pre></p>
</body>
</html>
Here is my auth.service.ts file
import { Injectable, OnInit } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { RequestOptions, Headers } from '@angular/http';
import { URLSearchParams } from '@angular/http';
@Injectable()
export class AuthService implements OnInit {
constructor(private http: HttpClient) { }
ngOnInit(): void {
}
login(username, password, rememberMe) {
console.log(username, password, rememberMe);
//const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
const body = JSON.stringify({ username: username, password: password });
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
this.http.post("/api/security/login", body, { headers: headers }).subscribe(
res => {
console.log(res);
},
(err: HttpErrorResponse) => {
console.log(err.error);
console.log(err.name);
console.log(err.message);
console.log(err.status);
}
)
}
logout() {
this.http.get("/api/auth/logout").subscribe(
res => {
console.log(res);
},
(err: HttpErrorResponse) => {
console.log(err.error);
console.log(err.name);
console.log(err.message);
console.log(err.status);
}
);
}
}
Solution: Finally resolve by entry in proxy.config.json given below "pathRewrite": {"^/api" : ""} so final json file is
{
"/api/*":{
"target":"http://10.104.40.14:8290/my_app",
"secure":false,
"pathRewrite": {"^/api" : ""}
}
}