Vujs (vue-cli) + API (laravel) on the same domain

Published 2 months ago by GeorgeD

I want to build a project with Vuejs(using vue-cli) as front-end and use Laravel for creating the API behind. A solution to the problem would be to not use vue-cli and include vue component in laravel, how Jeffrey teach in "Learn Vue 2: Step By Step" series. But I don't see any reason why the request should go through Laravel, instead just go straight to index.html file.

I want that if the user access www.domain.com it would access index.html(from vue-cli) directly. And as far as I know to get rid of OPTIONS requests the api should be accessible on exact domain www.domain.com/api.

How can I do this ?

cawex
cawex
2 months ago (19,130 XP)

It sounds like you just wanna split up your backend, and frontend which is a totally normal way to structure your application, it also give you some benfits like easier to test, a API that are already made in case you need a mobile app etc.

As to how, you would have two different projects app_backend and app_frontend, in the app_backend the entire API logic etc is, and in the app frontend, you would have some calls to the api that fetches and posts the data. And then if you wanna access it on the same domain I would probably make the nameserver/chost point to the /api in the backend

GeorgeD

Thank you so much... I didn't think about server configuration :))

The full solution:

Folder structure:

  • app/front_end
  • app/back_end

In nginx I had added:

location /api {
    alias "/home/vagrant/Code/app/back_end/public";
    try_files $uri $uri/ @api;
    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME /home/vagrant/Code/app/back_end/public/index.php;

        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
    }
}
location @api {
    rewrite /api/(.*)$ /api/index.php?/$1 last;
}

Also in nginx, for vue-router to work with HTML5 History Mode I had changed

try_files $uri $uri/ /index.php?$query_string;

in

try_files $uri $uri/ /index.html;

https://router.vuejs.org/en/essentials/history-mode.html

Result:

  • www.domain.com -> front-end (vuejs-cli)
  • www.domain.com/api -> back-end (laravel)
cawex
cawex
2 months ago (19,130 XP)

I guess that also could work, I can't really see the benefits of having it all in the same folder. Why not split it up to two applications rather than one=

Sign In or create a forum account to participate in this discussion.