[FIXED] Problem mit der Anmeldeauthentifizierung in Angular 2or

Ausgabe

Ich versuche, meine Anmeldeseite mit dem folgenden Code zu authentifizieren. Wenn ich versuche, mich anzumelden, erhalte ich einen Fehler “JSON.parse: unerwartetes Zeichen in Zeile 1, Spalte 1 der JSON-Daten”. Nach dem Debuggen zeigt der Fehler auf die Codezeile „let token:string = response && response.json().token;“. Was könnte das Problem in meinem Code sein. Danke im Voraus

//Authentication Service

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthenticationService {
    public token: string;

    constructor(private http: Http) {
        // set token if saved in local storage
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        this.token = currentUser && currentUser.token;
    }

    login(email: string, password: string): Observable<boolean> {
        return this.http.post('http://localhost:9000/api/crm_api/v1/user/login', JSON.stringify({
            email: email,
            password: password
        }))
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                let token:string = response && response.json().token;
                if (token) {
                    // set token property
                    this.token = token;

                    // store username and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify({email: email, token: token}));

                    // return true to indicate successful login
                    return true;
                } else {
                    // return false to indicate failed login
                    return false;
                }
            });
    }

    logout(): void {
        // clear token remove user from local storage to log user out
        this.token = null;
        localStorage.removeItem('currentUser');
    }
}
//login 
import { Component , OnInit} from '@angular/core';
import { NgForm} from '@angular/forms';
import {HttpService} from "../Services/HttpService";
import {Router} from '@angular/router'
import {AuthenticationService} from '../AuthenticationService/authenticationService'





@Component({
    selector: 'login',
    styleUrls:['app.logincomponent.css'],
    templateUrl : './app.logincomponent.html',
    providers:[AuthenticationService]
})
export class LoginFormComponent implements OnInit{
    loading = false;
    error = '';



    public redirectUrl: string = '/dashboard'; //Here is where the requested url is stored

    // constructor(private auth: AuthService) {}


    constructor(private auth:AuthenticationService, private router: Router)  {}

    ngOnInit() {
        // reset login status
        this.auth.logout();
    }


    login = {

        email: "",
        password: "",

    };

    //login user credentials to authenticate
    submitForm() {



        this.loading = true;
        this.auth.login(this.login.email, this.login.password)
            .subscribe(data => {
                if(data == true){
                    //login successful
                    this.redirect();

                }else {
                    this.error = "Username or Password is Invalid";
                    this.loading = false;
                }
            });



    }

    //redirect user after a successful login
    public redirect(): void {

        this.router.navigate([this.redirectUrl]); //use the stored url here

    }

}

//Error

{"_body":"<!doctype html>\n<html>\n<head>\n  <meta charset=\"utf-8\">\n  <title>CRMDirectory</title>\n  <base href=\"/\">\n  <link rel=\"stylesheet\" href=\"app/assets/css/bootstrap.min.css\">\n  <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css\">\n  <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>\n  <script src=\"https://cdn.ckeditor.com/4.5.11/full/ckeditor.js\"></script>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"../node_modules/primeng/resources/themes/omega/theme.css\" />\n\n\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"../node_modules/primeng/resources/primeng.min.css\" />\n\n\n  <link rel=\"stylesheet\" type=\"text/css\" href=\"/node_modules/primeng/resources/themes/omega/theme.css\" />\n  <link rel=\"stylesheet\" type=\"text/css\" href=\"/node_modules/primeng/resources/primeng.min.css\" />\n  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>\n  <script src=\"../node_modules/core-js/client/shim.min.js\"></script>\n  <script src=\"../node_modules/zone.js/dist/zone.js\"></script>\n  <script src=\"../node_modules/reflect-metadata/Reflect.js\"></script>\n  <script src=\"../systemjs.config.js\"></script>\n  <script>\n    System.script('app').catch(function(err){ console.error(err); });\n  </script>\n\n  <link rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\">\n</head>\n<body>\n  <app-root>Loading...</app-root>\n\n<script type=\"text/javascript\" src=\"inline.js\"></script><script type=\"text/javascript\" src=\"scripts.bundle.js\"></script><script type=\"text/javascript\" src=\"main.bundle.js\"></script></body>\n</html>\n","status":200,"ok":true,"statusText":"OK","headers":{"Content-Type":["text/html; charset=UTF-8"]},"type":2,"url":"http://localhost:4200/"}  main.bundle.js:53996:13
EXCEPTION: JSON.parse: unexpected character at line 1 column 1 of the JSON data  main.bundle.js:48941:9
ORIGINAL STACKTRACE:  main.bundle.js:48946:13
Body</Body.prototype.json@http://localhost:4200/main.bundle.js:51328:20
AuthenticationService</AuthenticationService.prototype.login/<@http://localhost:4200/main.bundle.js:53997:37
MapSubscriber</MapSubscriber.prototype._next@http://localhost:4200/main.bundle.js:10791:22
Subscriber</Subscriber.prototype.next@http://localhost:4200/main.bundle.js:498:13
XHRConnection/this.response</onLoad@http://localhost:4200/main.bundle.js:51143:21
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask@http://localhost:4200/main.bundle.js:107486:21
NgZone</NgZone.prototype.forkInnerZoneWithAngularBehavior/this.inner<.onInvokeTask@http://localhost:4200/main.bundle.js:35285:28
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask@http://localhost:4200/main.bundle.js:107485:21
Zone$1</Zone</Zone.prototype.runTask@http://localhost:4200/main.bundle.js:107375:28
ZoneTask/this.invoke@http://localhost:4200/main.bundle.js:107556:28
  main.bundle.js:48947:13
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

//Server

 public function login(Request $request){
        $this->validate($request, [
            'email' => 'required | email',
            'password' => 'required'
        ]);

        $credentials = $request->only('email', 'password');
        try{
            $token = JWTAuth::attempt($credentials);

            if(! $token){
                return response()->json([
                    'msg' => 'Invalid Credentials',
                    'retry' => true
                ], 401);
            }
        } catch (JWTException $e){
            return response()->json([
                'msg' => 'Could not create token',
                'retry' => true
            ], 501);
        }

        return response()->json([
            'token' => $token,
            'retry' => false,
            'status' => 'active'
        ], 200);

    }

Lösung

Es ist kein Winkelproblem!

Ihr Code würde funktionieren, aber Ihre Web-API antwortet nicht mit einer gültigen JSON-Zeichenfolge!

Es antwortet mit HTML-Code:

<!doctype html>\n<html>\n<head>\n  <meta charset=\"utf-8\">\n  <title>CRMDirectory</title>\n  <base href=\"/\">\n  <link rel=\"stylesheet\" href=\"app/assets/css/bootstrap.min.css\">\n  <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css\">\n  <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>\n  <script src=\"https://cdn.ckeditor.com/4.5.11/full/ckeditor.js\"></script>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"../node_modules/primeng/resources/themes/omega/theme.css\" />\n\n\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"../node_modules/primeng/resources/primeng.min.css\" />\n\n\n  <link rel=\"stylesheet\" type=\"text/css\" href=\"/node_modules/primeng/resources/themes/omega/theme.css\" />\n  <link rel=\"stylesheet\" type=\"text/css\" href=\"/node_modules/primeng/resources/primeng.min.css\" />\n  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>\n  <script src=\"../node_modules/core-js/client/shim.min.js\"></script>\n  <script src=\"../node_modules/zone.js/dist/zone.js\"></script>\n  <script src=\"../node_modules/reflect-metadata/Reflect.js\"></script>\n  <script src=\"../systemjs.config.js\"></script>\n  <script>\n    System.script('app').catch(function(err){ console.error(err); });\n  </script>\n\n  <link rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\">\n</head>\n<body>\n  <app-root>Loading...</app-root>\n\n<script type=\"text/javascript\" src=\"inline.js\"></script><script type=\"text/javascript\" src=\"scripts.bundle.js\"></script><script type=\"text/javascript\" src=\"main.bundle.js\"></script></body>\n</html>\n

Überprüfen Sie diese URL oder ändern Sie Ihren Server so, dass er mit gültigem JSON antwortet. 🙂


Beantwortet von –
Schrägstrich


Antwort geprüft von –
Dawn Plyler (FixError Volunteer)

0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like