您可以拥有您的API并在Laravel中吃(消费)它吗? [英] You can have your API and eat (consume) it in Laravel?

查看:48
本文介绍了您可以拥有您的API并在Laravel中吃(消费)它吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个在Laravel中返回json的API. ( routes/api.php )

I have made an API that returns json in Laravel. (routes/api.php)

现在,我想在项目的web端使用上述API( routes/web.php (包括中间件),刀片视图等).

Now I want to consume said API inside my web-side of the project (routes/web.php (including middleware), blade views etc.).

我目前的解决方案是这样的:

The current solution that I have is something like this:

public function register(Request $request) {
    // password1 == password2 etc (form logic / validation)
    $internal_request = Request::create($this->base_api_url . 'register', 'POST');
    $internal_request->replace($request->input());
    $response = Route::dispatch($internal_request);
}

如果该表单有效,则将请求转发"给与我的api对应的api.但是我觉得这不是最佳实践,也不是明智的选择.除loginregister以外的其他路由使用会话中存储的api令牌进行调用.他们将令牌"x-token"作为标头附加到$internal_request.在中间件中这样做更好吗?在某个地方有一些最佳实施的例子吗?

Which "forwards" the request to the api counterpart to my api if the form is valid. But I have the feeling this is not really best practice or smart. Other routes except login and register use the api token stored in session to make the calls. they append the token "x-token" as a header to $internal_request. Is it better to do this in middleware? Is there some example of a best implementation somewhere?

我的API具有这样的方法:

My API has a method like this:

POST api/register 哪个检查必填字段是否存在,并具有rigt格式(验证)

POST api/register Which check if the the required fields exist and have the rigt format (validation)

并且我的网络路由中有/register

and my web route has /register

这将首先检查密码验证输入(pass1 == pass2)中的密码是否匹配,然后将其传递给等效的api.

This will first check if the passwords match from the password validation inputs (pass1 == pass2) and will then pass it to the api equivalent.

所以web应该是api的超集(验证明智).

So web should be a superset (validation wise) of api.

推荐答案

我想我会这样做:

  • 在控制器中检测是否处理API请求或Web请求
  • 检测相应的凭证(令牌或会话)
  • 如果是网络则进行表单逻辑
  • 在两种情况下都执行api逻辑
  • 相应地创建视图或json响应
  • 全部在同一个控制器中

这篇关于您可以拥有您的API并在Laravel中吃(消费)它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆