Express - 将JavaScript数据传递给没有视图引擎的客户端

问题描述 投票:0回答:1

我有一个从快速服务器提供的应用程序。我正在使用vanilla JavaScript构建我的所有模板,而不使用任何模板文件或视图引擎。我想传递客户端JavaScript上下文中可用的数据以获取正常的导航请求。这样做的最佳做法是什么?

我根本不使用AJAX或单页应用程序。我的所有模板都在服务器上完全呈现。这是服务器的基本版本:

const express = require('express')
const app = express()

const meta = `<meta name="viewport" content="width=device-width, initial-scale=1">`
const account = `<button id="sign-out" class="js-authorized">Sign Out</button>`
const template = (title, content) => `<html>
<head>
  <title>${title}</title>

  ${meta}
</head>
<body>
  <div class='account'>
    ${account}
  </div>

  <div class='content'>
    <h1>${title}</h1>

    ${content} 
  </div>
</body>`

app.get('/', (request, response) => {
  const document = template('Index', 'Welcome')

  // How can I send this to the client?
  const data = {
    mainSeed: Math().random(),
    secondarySeeds: [Math().random(), Math().random(), Math().random()]
  }
  // This wouldn't work:
  // return response.send(data, document)

  return response.send(document)
})

我想确保页面上的任何JavaScript都可以访问数据,但我不想在服务器上使用除JavaScript模板文字之外的任何模板逻辑。通过基本Express向客户端发送数据的最佳做法是什么?

javascript node.js express routing httpresponse
1个回答
2
投票

我想传递客户端JavaScript上下文中可用的数据以获取正常的导航请求。这样做的最佳做法是什么?

通过使用视图引擎呈现您的数据或限制/强制您的ajax请求来请求application/json,以便您可以使用JSON进行响应。

你要做的就是React,Vue和Angular已经为你做的事了。如果您确实不想使用vanilla HTML,请使用React或许多SPA框架/库之一。

你想要完成什么是行不通的。 res.send只接受一个论点:res.send([body])。你不能像你想要的那样发送任何其他东西。黑客解决方法(未经测试)将是这样的:

const template = (title, content, data) => `<html>
<head>
  <title>${title}</title>

  ${meta}
</head>
<body>
  <div class='account'>
    ${account}
  </div>

  <div class='content'>
    <h1>${title}</h1>

    ${content} 
  </div>
</body>
<script>
  window.data = ${data}
<script>
`

const document = template('Index', 'Welcome', {data: {} })

在这一点上,这与使用视图引擎有何不同?它完成了同样的事情。如果您要使用视图引擎,那么您将能够使用res.render

app.get('/', (request, response) => {
  const data = {
    mainSeed: Math().random(),
    secondarySeeds: [Math().random(), Math().random(), Math().random()]
  }

  response.render('Index', { data, content: 'Welcome' })
})
© www.soinside.com 2019 - 2024. All rights reserved.