请参见下面的UserController代码。我试图通过 api 使用 VUEJS 。因此,我创建了路由来在api.php 进行注册和登录。为了测试即时通讯试图通过邮递员并通过 http://localhost:8000/api/register 和接受的application / json以及Content-type和application / json 传递数据。我通过正文传递数据作为表单数据。问题是,当我尝试发送数据时,邮递员连续发送数据而没有响应,而当我取消请求时,端口8000不再起作用。因此,我必须停止服务器并再次运行。谁能告诉我我的代码中有任何错误。我正在使用laravel 5.7
<?php
namespace App\Http\Controllers\Api;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function register(Request $request){
$request->validate([
'name' => 'required',
'email'=> 'required',
'password'=> 'required'
]);
//add some cde that what happen if validation fils
$newUser = User::firstOrNew(['email'=> $request->email]);
$newUser->name = $request->name;
$newUser->email =$request->email;
$newUser->password = bcrypt($request->password);
$newUser->save();
$http = new Client;
$response = $http->post(url('oauth/token'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => '2',
'client_secret' => '9J0sU4Ctz5p3AUz7ROiv7jELnGrU5waepprqICyH',
'username' => $request->email,
'password' => $request->password,
'scope' => '',
],
]);
return response(['data' => json_decode((string)$response->getBody(), true) ]) ;
}
public function login(Request $request){
$request->validate([
'email'=> 'required',
'password'=> 'required'
]);
$user = User::where('email', $request->email)->first();
if(!$user){
return response(['status' => 'error' , 'message'=> 'user not found']);
}
if(Hash::check($request->password, $$user->password)){
$http = new Client;
$response = $http->post(url('oauth/token'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => '2',
'client_secret' => '9J0sU4Ctz5p3AUz7ROiv7jELnGrU5waepprqICyH',
'username' => $request->email,
'password' => $request->password,
'scope' => '',
],
]);
return response(['data' => json_decode((string)$response->getBody(), true)]);
}
}
}
答案 0 :(得分:0)
我的登录代码几乎相同。这个正在为我工作:
public function login(Route $route, Request $request)
{
// validation stuff...
$user = User::where('email', $request->email)->first();
if ($user && Hash::check($request->password, $user->password)) {
$http = new Client();
$response = $http->post(url('oauth/token'), array(
'form_params' => array(
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => '...',
'username' => $request['email'],
'password' => $request['password']
)));
return json_decode($response->getBody(), true)['access_token'];
} else {
abort(401);
}
}
而且:您在第二个“如果”中写了 $$ user ...