有人可以告诉我我在做什么错

时间:2019-03-27 12:10:07

标签: angular lumen

我正在尝试使用流明后端进行登录服务。在邮递员中,它可以按预期工作,但是当我尝试使用onSubmit函数发送表单数据时,它会返回200,但返回html而不是api令牌。任何帮助将不胜感激。

/* lUMEN API LOGIN CONTROLLER */
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Hash;
use App\User;

class LoginController extends Controller
{
    public function login(Request $request)
    {

      $rules = [
          'email' => 'required',
          'password' => 'required'
      ];

        $customMessages = [
           'required' => ':attribute tidak boleh kosong'
      ];
        $this->validate($request, $rules, $customMessages);
         $email    = $request->input('email');
        try {
            $login = User::where('email', $email)->first();
            if ($login) {
                if ($login->count() > 0) {
                    if (Hash::check($request->input('password'), $login->password)) {
                        try {
                            $api_token = sha1($login->id_user.time());

                              $create_token = User::where('id', $login->id_user)->update(['api_token' => $api_token]);
                              $res['status'] = true;
                              $res['message'] = 'Success login';
                              $res['data'] =  $login;
                              $res['api_token'] =  $api_token;

                              return response($res, 200);


                        } catch (\Illuminate\Database\QueryException $ex) {
                            $res['status'] = false;
                            $res['message'] = $ex->getMessage();
                            return response($res, 500);
                        }
                    } else {
                        $res['success'] = false;
                        $res['message'] = 'Username / email / password not found';
                        return response($res, 401);
                    }
                } else {
                    $res['success'] = false;
                    $res['message'] = 'Username / email / password  not found';
                    return response($res, 401);
                }
            } else {
                $res['success'] = false;
                $res['message'] = 'Username / email / password not found';
                return response($res, 401);
            }
        } catch (\Illuminate\Database\QueryException $ex) {
            $res['success'] = false;
            $res['message'] = $ex->getMessage();
            return response($res, 500);
        }
    }
}
/* Angular Login Component */
import { Component, OnInit } from '@angular/core';
import { LoginService } from '../login.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {
  user: any = [ ];
  constructor(private api: LoginService) { }

  ngOnInit() {
  }


onSubmit() {
  this.api.login(this.user).subscribe(
    data => {
      if (false) {
        localStorage.setItem('currentUser', JSON.stringify(this.user));
    } else {
      console.log(this.user);
     }
    },

 );
 }
}
/* Angular login Service*/
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { EnvService } from '../services/env.service';
import { catchError, map } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class LoginService {

  constructor(public http: HttpClient,
              public env: EnvService) { }

              login(user) {
                return this.http.post(this.env.LOCAL_ENDPOINT + '/login',  user, {responseType: 'text'});
                  }
            logout() {
                // remove user from local storage to log user out
                localStorage.removeItem('currentUser');
            }
}
<div class="uk-position-center">
  <h1>Login</h1>
  <div clsss="uk-card">
    <div class="uk-card-content">
      <form name="login" (ngSubmit)="onSubmit()">
      <input placeholder="Email" class="uk-input" type="email" name="email" [(ngModel)]="user.email">
      <br/>
      <input placeholder="password" class="uk-input" type="password" name="password" [(ngModel)]="user.password">
      <hr class="uk-divider-icon">
      
      <button style="align-content: center" value="Login" class="btn btn-primary">Login</button>
      </form>
    </div>
  </div>
</div>
这是我在浏览器中得到的响应,所以我知道我不是通过怀特方式传递数据,但我不知道正确的方式是什么 Web response

这是我要显示的响应并将api令牌保存在本地存储中 enter image description here

网络控制台 enter image description here

2 个答案:

答案 0 :(得分:0)

就像@Joel所说的那样,问题在于后端期望用户名和密码作为查询参数。您可以像这样编辑登录服务:

this.http.post( this.env.LOCAL_ENDPOINT + '/login?user=' + user.email + "&password=" + user.password, { responseType: 'text' } );

但是,在URL中以纯文本形式发送密码是非常不明智的做法,因此,我建议您重新考虑,而应更改后端,以便它期望用户名并传入标头。

答案 1 :(得分:0)

根据邮递员的屏幕快照,当您将数据作为查询参数发送时,后端可以工作,但您应该将其作为表单数据发送。

login(user){
   let userData = new FormData();
   userData.append('email', user.email);
   userData.append('password', user.password);
   return this.http.post(this.env.LOCAL_ENDPOINT + '/login',userData);
}