在 Laravel 中使用 SSR 的 Nuxt——最基础 SSR 页面

1. 首先新建一个全新的 Laravel 项目 weibo

composer create-project laravel/laravel weibo

(演示里我将给这个项目分配 weibo.test 域名)

2. 我们将把 nuxt 工程的所有文件放到 laravel 项目中的 client 文件夹中

修改默认的 package.json 如下

{
    "private": true,
    "scripts": {
        "dev": "node_modules/nuxt/bin/nuxt.js -c client/nuxt.config.js",
        "build": "node_modules/nuxt/bin/nuxt.js build -c client/nuxt.config.js",
        "start": "node_modules/nuxt/bin/nuxt.js start -c client/nuxt.config.js",
        "lint": "eslint --fix --ext .js,.vue client/",
        "prod": "npm run build && npm run start"
    },
    "config": {
        "nuxt": {
            "host": "0.0.0.0",
            "port": "3000"
        }
    },
    "dependencies": {
        "nuxt": "^2.13.0"
    }
}

同时我们添加一个最基础的 client/nuxt.config.js

module.exports = {
    srcDir: __dirname,
    watchers: {
        webpack: {
            aggregateTimeout: 300,
            poll: 1000
        }
    }
}

然后执行

npm install && npm run dev

如果你是用的 Homestead, 可能需要 root 权限和 --no-bin-links 安装 npm
这个时候打开 weibo.test:3000 已经可以看到 Nuxt 的默认页面
Nuxt 默认页面

3. 修改 Nginx 配置 /etc/nginx/sites-available/weibo.test

# 修改前
location / {
    try_files $uri $uri/ /index.php?$query_string;
}
# 修改后
location /api/ {
    try_files $uri $uri/ /index.php?$query_string;
}
location / {
    proxy_pass http://127.0.0.1:3000;
}

重启一下 Nginx service restart nginx

4. 现在我们来实现一个 SSR 的页面

准备一个演示接口

php artisan make:controller PagesController

app/Http/Controllers/PagesController.php

public function index(){
    return response()->json([
        'title' => 'SSR 测试'
    ]);
}

routes/api.php

Route::get('/pages', 'PagesController@index');

安装 axios 后,新建 client/pages/index.vue

<template>
    <h1>
        {{ title }}
    </h1>
</template>
<script type="text/javascript">
import axios from 'axios';
export default{
    async asyncData () {
        const { data } = await axios.get(`http://weibo.test/api/pages`);
        return { title: data.title }
    }
}
</script>

大功告成
最基础的 SSR

5. 生产模式

npm run prod 再使用 pm2 保持 run

# 全局安装 pm2
npm install -g pm2
# 启动 pm2
pm2 startup
# 开启一个 pm2 进程
pm2 start npm --name "weibo" -- run start
# 持续 run
pm2 save

每次更新后都要重新启动 pm2

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 3

这个auth登录状态如何保存的,通过这个方式,nuxt的登录状态没有了,cookie传不到nuxt服务上

2年前 评论
家猪配种专家 (楼主) 1年前
家猪配种专家 (楼主) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!