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" : ""}
}
}
Try to write your post request this way:
login(username, password, rememberMe)) {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
//You can append here whatever you like in your headers;
headers.append(username, password);
options: RequestOptions = new RequestOptions(headers);
this.http.post(/api/security/login, options)
.suscribe(res => res.json())
}
The 401
is an error coming from the server handling the request. You need to see, if the server is getting the headers of your request or not.
Regarding your proxy config, you can do the following:
{ "/api": { "target": "yourUrl.com",
"secure": false,
"pathRewrite": {"^/api" : ""}
}
}
The pathRewrite
option will remove api
from your url.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments