Vue服务器端渲染

时间:2020-09-22 14:24:14

标签: vue.js vuex server-side-rendering

如果在服务器上呈现页面时我们将SPA应用程序转换为SSR + SPA,则通过调度将通过axios进行http调用的操作从vuex存储中加载数据到localhost上的api中来。

还是需要从数据库中加载数据,以及如何将这些数据传递到vue并防止调度存储操作?

在传统应用程序中,我将直接从数据库中检索该数据,而不进行get请求。

正常吗? 是这样吗?

Nuxt还使用get请求而不是数据库查询:

export default {
  asyncData({ params, error }) {
    return axios
      .get(`https://my-api/posts/${params.id}`)
      .then(res => {
        return { title: res.data.title }
      })
      .catch(e => {
        error({ statusCode: 404, message: 'Post not found' })
      })
  }
} 

我可以在serverPrefetch()中不用nuxt来做到这一点。

另一方面,如果我做类似的事情

export default {
  asyncData({ req, res }) {
    and here if I access database like in node server
   (req, res) => {
      **select something from database **
      return User.findOne({ });
   }
  }
}

后端敏感代码在前端脚本中可见吗?!

1 个答案:

答案 0 :(得分:0)

使用nuxt表示:

/plugins/api-context.server.js

export default (context, inject) => {
  inject("api", async (controller, method, params) => {
    try {
      let api = require("../api/" + controller.replace(/^\/+|\/+$|\.+/g, ""));
      return await api[method](params);
    } catch (e) {
      console.error(e);
      throw e;
    }
  });
};

/nuxt.config.js

  plugins: [
    "~/plugins/api-context.client.js",
    "~/plugins/api-context.server.js"
  ]

现在此函数。$ api将直接在服务器上调用控制器方法,并在客户端上。$ api通过axios发送http请求。

在没有nuxt的情况下该如何做?