我有一个用Laravel后端和react前端完成的完整项目。 react应用程序包装在Laravel代码中,只有在登录并进行了一些选择后才能使用,这些操作均在laravel中完成,并带有其视图。我想将react应用程序作为一个独立的应用程序,并将laravel代码制作为一个api,可以通过服务器从中获得服务。一个网址,以便react应用通过向laravel api发出请求即可正常工作。
所以我的第一个问题是:有没有办法对我的laravel代码实施API,以模仿我已经准备好的现有登录实现?
由于我的问题涉及面很广,因此我不确定该问题要提供什么代码。该代码遵循MVC设计模式,因此随时可以要求代码的某些部分。
作为一个轻微的题外问题(如果您只是想帮助laravel东西,请不要阅读此书):我想将laravel后端和react前端应用程序分离的原因是包装react使用laravel后端在电子应用中使其成为离线应用。这是一个合理的方法吗?
编辑:我发现问题的症结在于如何执行laravel提供的登录表单与“ API样式”登录。因此,我认为我需要使用laravel Passport实施登录,以通过laravel登录表单登录来检索具有与该用户相匹配的凭据的用户。但是laravel登录表单中的逻辑对我来说很难理解,因此我可以在此方面助一臂之力。
下面是我的登录控制器和关联的中间件的代码。再说一遍,告诉您是否需要更多代码。
登录控制器(来自App / http / controllers / auth):
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|---------------------------------------------------------------------
| Login Controller
|------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
中间件(来自App / http / Kernel.php):
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware \AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
编辑2:
这是我的web.php路由的代码:
<?php
/*
|---------------------------------------------------------------
| Web Routes
|----------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
Route::get('/', 'HomeController@index')->name('home');
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/setlocale/{locale}', function (Request $request, $locale) {
if (in_array($locale, \Config::get('app.locales'))) {
session()->put('locale', $locale);
}
return redirect()->back();
});
Route::get('/profile', 'UserController@show')->name('profile');
Route::patch('/profile', 'UserController@update')->name('users.update');
Route::get('/scan', 'HomeController@index')->name('scan.index');
Route::get('/scan/new', 'ScanController@new')->name('scan.new');
Route::get('/scan/{id}', 'ScanController@show')->name('scan.show');
Route::post('/scan', 'ScanController@create')->name('scan.create');
Route::patch('/scan/{id}', 'ScanController@update')->name('scan.update');
Route::delete('/scan/{id}', 'ScanController@destroy')->name('scan.destroy');
// save SCAN JSON
Route::post('/scan/{id}/save', 'ScanController@save')->name('scan.save');
编辑3:
第一件事,当我创建访问令牌时,存储在/ oauth / personal-access-tokens中的内容如下:
0:
client:
created_at: "2019-01-04 13:00:48"
id: 3
name: "SCAN Personal Access Client"
password_client: false
personal_access_client: true
redirect: "http://localhost"
revoked: false
updated_at: "2019-01-04 13:00:48"
user_id: null
__proto__: Object
client_id: 3
created_at: "2019-01-15 13:52:22"
expires_at: "2020-01-15 13:52:22"
id: "0321b2d622bd7267273225a64cf6f1723cc74b86076831432fb5af4885051c6776bb8ea77c0d7407"
name: "MyApp"
revoked: false
scopes: []
updated_at: "2019-01-15 13:52:22"
user_id: 1
__proto__: Object
在13:00:48创建的第一个客户端中,uder_id为null。有问题吗?
第二,这是我尝试使用axios进行请求,使用函数登录名获取访问令牌(并且确实获取访问令牌)以及我的API在localhost:4321上运行的方式
login = async () => {
return axios.post('http://localhost:4321/api/login', {
grant_type: 'password',
client_id: 5,
client_secret: 'd3zuZL6KbBI4DOq4Z7NQkP1ezrAj5GMjgo39',
email: 'my mail, used to login',
password: 'my password',
scope: '',
})
}
async componentDidMount() {
const accessTokenData = await this.login();
var config = {
headers: {
Authorization: "bearer " + accessToken
},
grant_type: 'password',
client_id: 'PassGrantClient',
client_secret: 'd3zuZL6KbBI4zsDOq4Z7NQkP1ezrAj5GMjgo39',
scope: '',
};
axios.post(
'http://localhost:4321/api/getInterview',
{},
config
).then((response) => {
console.log(response)
})
}
getInterview路由指向函数的地方
public function getInterview()
{
$user = Auth::user();
return response()->json($user);
}
返回401,如您所见,我不确定将什么放在:)。如果您需要更多代码,请随时询问:)。
答案 0 :(得分:1)
您需要将Routes / web转换为Routes / api
然后,您可以在要在应用程序中使用的laravel Passport API或jwt API之间进行选择
(如果您选择jwt,则需要在控制器中创建一个文件夹并将其命名为API,并在Routes / api中添加API \ 例如: 路线:post ::('/ example','API \ yourcontroller @ yourfunction'); )
并且要与api进行连接,您需要将请求发送给您
www.yourdomain.com/api/您的api溃败
这一切都希望对您有用
编辑:
这比您想像的要容易得多,使用API时,您将不需要(在向您的项目中添加laravel通行证后,即可登录“登录控制器(来自App / http / controllers / auth)”)。文档documentaion )来创建您的一个用于身份验证的控制器
示例 logincontroller:
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
return response()->json(['success' => $success],200);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
要注册,您可以使用
public function register(Request $request){
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')-> accessToken;
$success['name'] = $user->name;
return response()->json(['success'=>$success], $this-> successStatus);
}
您需要知道使用护照api登录时,如果要获取用户数据,将给您accsses_token而不是用户数据,
像这样在您的api中创建路由
Route::group(['middleware' => 'auth:api'], function(){
Route::post('details', 'API\LoginController@details');
}
和您的控制器添加功能
public function details()
{
$user = Auth::user();
return response()->json(['success' => $user], 200);
}
然后将accsses_token发送到根目录以获取用户数据
Edite 2:
如果仅在成功登录后才想使路由起作用,则非常需要使用中间件'auth:api保护该路由。 示例:
Route::group(['middleware' => 'auth:api'], function(){
Route::post('test', 'API\testController@test');
Route::get('test2', 'API\testController@test2');
Route::post('test3', 'API\testController@test3');
}
答案 1 :(得分:0)
我认为使用相同的模式和逻辑迁移到Laravel 5及更高版本会有所帮助,他们现在有了一个名为api.php的新路由文件,而且所有响应都将转换为一个JSON对象,供前端使用。
如果您不想迁移到Laravel,只需将所有响应转换为JSON对象