首页 > 解决方案 > 如何从 Laravel 路由提供生成的 Vue 应用程序?

问题描述

我没有默认设置 vue + laravel,vue 与 laravel 完全分开。在我的情况下,laravel 仅作为 API。我完成了一个 vue 应用程序并build执行了生产命令。

我以这种形式获得了生成的资源:

在此处输入图像描述

我正在考虑如何将这样的应用程序上传到托管服务器并得出结论,我需要通过我的 laravel 服务器发送 vue 文件。

我在routes/web.php中写了路由:

Route::get('{uri}', function ($uri = '/') {
    $sourceByUri = public_path('_frontend/' . $uri);

    if (is_file($sourceByUri)) {
        return file_get_contents($sourceByUri);
    }

    $indexSpa = public_path('/_frontend/index.html');

    return file_get_contents($indexSpa);
})->where('uri', '.*');

我的 api 可以正常工作,但是 _frontend 文件夹中的文件未正确发送(css 不适用)。截屏

应该是这样的:截图

事实证明,来自服务器的所有响应都是值得的Content-Type: text/html

如何通过服务器正确打开我的应用程序?

标签: phplaravelvue.js

解决方案


您应该直接通过 Nginx 为您的前端应用程序提供服务,并配置反向代理以通过 Laravel 访问 API:

首先,配置你的 laravel 应用程序以便 Nginx 可以为它服务(我让 Nginx 监听这个配置的随机端口):

server {
    listen 1222;

    root /var/www/html/your-app/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # Insert PHP configs here etc...
}

然后,为您的 web 应用程序提供服务,并将去往/api端点的调用转到您的 laravel 应用程序,而不是您的前端应用程序。如果你想通过 http 服务,让它监听端口 80,如果你想通过 https 服务,让它监听端口 443:

server {
    listen 80;
    server_name your-app.com;

    root /var/www/your-app/public/_frontend;

    location /api {
        # Backend server to forward requests to/from
        proxy_pass          http://localhost:1222;
        proxy_http_version  1.1;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        client_max_body_size 500M;
    }

    location / {
        try_files $uri /index.html;
    }
}

推荐阅读