server-render.js
const ejs = require("ejs")
module.exports = async(ctx, renderer, template) => {
ctx.headers["Content-Type"] = "text/html"
const context = { url: ctx.path }
console.log(ctx.path)
console.log("renderer", renderer);
try {
const appString = await renderer.renderToString(context)
console.log("appString", appString);
const {
title
} = context.meta.inject()
const html = ejs.render(template, {
appString,
title: title.text(),
style: context.renderStyles(),
scripts: context.renderScripts()
})
ctx.body = html
} catch (err) {
console.log("appString", "errr");
console.log("render error", err)
throw err
}
}
ssr.js
const Router=require("koa-router")
const path=require("path")
const fs=require("fs")
const VueServerRender=require("vue-server-renderer")
const serverRender=require("./server-render")
const clientManifest=require("../../public/vue-ssr-client-manifest.json")
const renderer= VueServerRender.createBundleRenderer(
path.join(__dirname,"../../server-build/vue-ssr-server-bundle.json"),
{
inject:false,
clientManifest
}
)
console.log("renderer",renderer)
const template=fs.readFileSync(
path.join(__dirname,"../server.template.ejs"),
"utf-8"
)
const pageRouter=new Router()
pageRouter.get("*",async (ctx)=>{
await serverRender(ctx,renderer,template)
})
module.exports=pageRouter
error message
A renderer.renderToString (context)
error was reported by printing
put the code in githunb
https://github.com/fridaydream/vue-ssr-example.git
after executing the commands npm run build
and npm start
, I reported an error