0
votes

I am using Angular with REST api to connect to backend.I'm passing username and password in order to access the resources, the servletFilter is looking fine, the problem is in the browser when it sends the response. This error is generated. I've read many questions like this I couldn't find one that solve my problem

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", 
url: "http://localhost:8080/front", ok: false, …}
error:
error: SyntaxError: Unexpected token < in JSON at position 0 at 
JSON.parse (<anonymous>) at XMLHttpRequest.onLoad 
(http://localhost:4200/vendor.js:10132:51) at ZoneDelegate.invokeTask 
(http://localhost:4200/polyfills.js:3626:31) at Object.onInvokeTask 
text: "
__proto__: Object
headers: HttpHeaders
lazyInit: () => {…}
lazyUpdate: null
normalizedNames: Map(0) {}
 __proto__: Object
message: "Http failure during parsing for 
http://localhost:8080/front"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/front"
__  proto__: HttpResponseBase

this is the loginService

constructor (private http : HttpClient){}
sendCredential(username: string, password: string){
    let url = "http://localhost:8080/index";
    let params = 'username='+username+'&password='+password;
    let headers = new HttpHeaders(
    {
        'Content-Type': 'application/x-www-form-urlencoded'
        // 'Access-Control-Allow-Credentials' : true
    });
    return this.http.post(url,params,{headers: headers, withCredentials : true}).pipe(res => {
    return res;
    });

here is the login component method which is calling the login service method

onSubmit() {
this.loginService.sendCredential(this.username, this.password).subscribe(
  res => {
    this.loggedIn=true;
    localStorage.setItem('PortalAdminHasLoggedIn', 'true');
    location.reload();
  },
  err => console.log(err)
);
 }

Thanks for help

2
First you check response type in network tab under developer tool. if not json then prepare server side data in json format.Rahul Dapke

2 Answers

0
votes

This error comes when the response from the REST service is returning the html page that starts with angel brackets so that's why this error come

Unexpected token < in JSON at position 0 at 

JSON.parse ()

For the response to not throw an error you have to set the response to be a JSON response from the service side that starts with a json style curly bracket {

You check the response by opening the developer tools and under network tab. Then make a request of login then click on that record and see the details it is showing bin the right under the response tab you will find an html page

0
votes

That may be because the response from the server is not returning a valid JSON. check your network tab and see for incoming server response.