Laravel+Vue 前后端分离 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
linkbg
V2EX    PHP

Laravel+Vue 前后端分离

  •  
  •   linkbg Feb 22, 2017 13201 views
    This topic created in 3350 days ago, the information mentioned may be changed or developed.

    目前实践一个项目。有些小问题。可能想法错了,还望大家指点一下。 目录结构:

    ---vue-laravel | | ---- client #这是纯的 vue 目录 | ---- server #laravel 放在这里 

    laravel 提供 api 并且通过 CORS 解决跨域的问题。

    目前认证这块是正常的。

    但是我想把注册的模块也通过 vue 来实现页面展示, laravel 来存入数据库。但是,我使用 CORS 来提交数据会报 422 的错误。好像应该我没有把 CSRF 值传入的问题。

    代码如下: vue 提交注册数据

    handleRegisterFormSubmit () { const postData = { grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret, email: this.register.email, password: this.register.password, password_confirmation: this.register.password_confirmation, name: this.register.name, scope: '' } this.$http.post('http://localhost:8000/api/register', postData) .then(respOnse=> { console.log(response) }) } 

    laravel Api 路由:

    Route::post('/register',"Auth\RegisterController@register"); 

    请问应该怎么来处理种没有认证之前的前后端数据交互呢?谢谢

    Supplement 1    Feb 22, 2017
     this.$http.post(loginUrl, postData) .then(respOnse=> { // 设置客户端认证 if (response.status === 200) { console.log(response) clientAuth.access_token = response.data.access_token window.localStorage.setItem('clientAuth', JSON.stringify(clientAuth)) } // 携带客户端认证信息和要post的数据 this.$http.post('http://127.0.0.1:8000/api/register', postDataRegister, {headers: getHeaderClient()}) .then(respOnse=> { console.log(response) }) }) 

    header

     export const getHeaderClient = function () { const tokenData = JSON.parse(window.localStorage.getItem('clientAuth')) const headers = { 'Accept': 'application/json', 'Authorization': 'Bearer ' + tokenData.access_token, } return headers } 

    客户端认证成功,但是提交数据就401

    Supplement 2    Feb 22, 2017

    经过一下午反复思考,最终还是决绝了。但是如果laravel中register的validator如果出现,比如两个密码不一致或者密码长度小于6,反者就是这个验证过不了就会出现 422 (Unprocessable Entity)的错误。这一块准备在前端这边进行一个判断然后再post请求。

    code如下:

     methods: { handleRegisterFormSubmit () { const postData = { grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret, scope: '' } const postDataRegister = { grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret, email: this.register.email, password: this.register.password, password_confirmation: this.register.password_confirmation, name: this.register.name, scope: '' } const clientAuth = {} this.$http.post(loginUrl, postData) // 获取客户端认证 .then(respOnse=> { if (response.status === 200) { console.log(response) clientAuth.access_token = response.data.access_token window.localStorage.setItem('clientAuth', JSON.stringify(clientAuth)) // 本地存储认证信息 } this.$http.post('http://127.0.0.1:8000/api/register', postDataRegister, {headers: getHeaderClient()}) .then(respOnse=> { console.log(response) // post请求创建 }) }) } } 

    一些常量:

    export const apiDomain = 'http://localhost:8000/' export const loginUrl = apiDomain + 'oauth/token' export const userUrl = apiDomain + 'api/user' 

    总算解决了。

    21 replies    2017-02-23 08:51:40 +08:00
    airycanon
        1
    airycanon  
       Feb 22, 2017   1
    Laravel 5.4 里面用的是 axios 发请求,原理如下:

    把变量传到页面中:
    ```
    <script>
    window.Laravel = {!! json_encode([
    'csrfToken' => csrf_token(),
    ]) !!};
    </script>
    ```
    在 axios 的 header 中设置 csrfToken :
    ```window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest'
    };
    ```
    用 Vue 的话同理。
    airycanon
        2
    airycanon  
       Feb 22, 2017
    不好意思,没看清是前后端分离,这样的话我只知道设置 CSRF 中间件的 $except ,可以排除掉某些路由,或者直接在 Http\Kernel.php 中禁用 CSRF 中间件了。
    branchzero
        3
    branchzero  
       Feb 22, 2017   1
    你确定走了 api 的 middleware 了么,如果走 api 的 middleware 的话默认是不会启用 csrf check 的
    linkbg
      nbsp; 4
    linkbg  
    OP
       Feb 22, 2017
    @branchzero 谢谢。但是新的问题是 401 但是我明明已经取得客户端授权了。请问这个怎么解决呢?我将新的情况补充在问题上。
    ydxred
        5
    ydxred  
       Feb 22, 2017
    分离不是应该写在视图里面吗?
    linkbg
        6
    linkbg  
    OP
       Feb 22, 2017 via iPhone
    @ydxred 视图这里完全交给 vue 。 laravel 的视图就不去写了。
    coooooooode
        7
    coooooooode  
       Feb 22, 2017
    和我想的一样,前端就只做前端的事,让 vue 控制数据与 api 调用。 支持!
    jellybool
        8
    jellybool  
       Feb 22, 2017
    我觉得你阔以看看这个
    jellybool
        9
    jellybool  
       Feb 22, 2017   1
    benbenlang
        10
    benbenlang  
       Feb 22, 2017
    @jellybool 你的视频要付费啊,,,
    jellybool
        11
    jellybool  
       Feb 22, 2017
    @benbenlang 是的
    skyjerry
        12
    skyjerry  
       Feb 22, 2017 via iPhone
    @jellybool 出示学生证可否优惠?学生,没什么钱
    jellybool
        13
    jellybool  
       Feb 22, 2017
    @skyjerry 这个暂时没有,不好意思
    linkbg
        14
    linkbg  
    OP
       Feb 22, 2017
    @jellybool 价格有点小贵了。但是能分享一下,您是这样写的吗?我新的附言。
    linoder
        16
    linoder  
       Feb 22, 2017
    都分离了 csrf 还有用么?
    linkbg
        17
    linkbg  
    OP
       Feb 22, 2017
    scrf 没有用了。是传入 access_token 。
    linkbg
        18
    linkbg  
    OP
       Feb 22, 2017
    scrf 没有用了。是传入 access_token 。

    @linoder
    yangqi
        19
    yangqi  
       Feb 22, 2017
    都前后端分离了,直接把 csrf 的 middleware 关掉就行了
    crossmaya
        20
    crossmaya  
       Feb 23, 2017
    一看就是 auth 中间件的问题!
    chaegumi
        21
    chaegumi  
       Feb 23, 2017
    为什么没人说
    client_id: clientId,
    client_secret: clientSecret,
    同时存在在 js 代码中,是否有问题。限制该 client_id 只能使用特定的 grant_type ?
    About     Help     Advertise     Blog     API     FAQ     Solana     1073 Online   Highest 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 61ms UTC 23:28 PVG 07:28 LAX 16:28 JFK 19:28
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86