php - 如何从 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
如何通过服务器正确打开我的应用程序?
解决方案
您应该直接通过 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;
}
}
推荐阅读
- c# - Console.WriteLine 无效条目,因此显示错误
- php - 使用 PHP 删除 XLF 中的重复条目
- java - java收到kill信号后,为什么主线程没有运行完成?
- python - 如何在 Serverless Lambda (Python) 中下载 S3 文件
- android - Google Assistant 语音搜索集成不适用于多个单词
- node.js - 用 3 个表对嵌套关联进行 Sequelize
- python - 如何在所有列排列上最小化正矩阵的轨迹
- ios - iOS Safari:经常发送的 ajax 调用有时无法到达服务器
- java - 套接字异常:twilio API 的连接重置
- php - Lumen:处理服务层内的错误消息