You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Node.js/Express中不使用res.render调用EJS并返回含其生成HTML的JSON?

How to Use EJS Without res.render() in Node.js/Express & Return Rendered HTML in JSON

Absolutely, this is totally doable! You don’t need to tie EJS exclusively to Express’s res.render() method—EJS has its own standalone rendering functions that let you generate HTML strings directly. You can then easily slot that HTML into a JSON object and send it via res.send(). Here’s how to pull this off:

Step 1: Install Dependencies

First, make sure you have both express and ejs installed:

npm install express ejs

Step 2: Basic Implementation (Callback Style)

You can use EJS’s renderFile() method to load and render a template file. This method takes the path to your EJS template, data to pass into the template, and a callback that returns the rendered HTML (or an error).

Here’s a complete example:

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

// Optional: Set the default views directory to make template paths cleaner
app.set('views', './views');

app.get('/get-html', (req, res) => {
  // Data to pass to your EJS template
  const templateData = {
    username: 'Emilio',
    message: 'Hello from EJS!'
  };

  // Render the template file
  ejs.renderFile('./views/template.ejs', templateData, (err, html) => {
    if (err) {
      // Handle rendering errors (e.g., missing template, syntax errors)
      return res.send({
        status: 'error',
        timestamp: new Date(),
        error: err.message
      });
    }

    // Send the JSON response with rendered HTML
    res.send({
      status: 'success',
      timestamp: new Date(),
      htmlContent: html
    });
  });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Step 3: Async/Await Style (Cleaner, No Callbacks)

If you prefer using async/await over callbacks, you can promisify renderFile() using Node.js’s util.promisify utility:

const express = require('express');
const ejs = require('ejs');
const { promisify } = require('util');
const app = express();

app.set('views', './views');
// Convert renderFile to a promise-based function
const renderEjs = promisify(ejs.renderFile);

app.get('/get-html', async (req, res) => {
  try {
    const templateData = {
      username: 'Emilio',
      message: 'Hello from async EJS!'
    };

    const html = await renderEjs('./views/template.ejs', templateData);
    
    res.send({
      status: 'success',
      timestamp: new Date(),
      htmlContent: html
    });
  } catch (err) {
    res.send({
      status: 'error',
      timestamp: new Date(),
      error: err.message
    });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Example template.ejs

Just to tie it all together, here’s a simple template.ejs you could put in your views folder:

<div class="greeting">
  <h1>Hi <%= username %>!</h1>
  <p><%= message %></p>
</div>

Key Notes

  • Template Paths: Make sure the path to your EJS file is correct. If you set app.set('views', './views'), you can just pass 'template.ejs' to renderFile() instead of the full path.
  • Error Handling: Always wrap your rendering logic in error handling (either callbacks or try/catch) to catch issues like missing templates or invalid EJS syntax.
  • String Templates: If you have your EJS template as a string instead of a file, you can use ejs.render(templateString, data) directly—no need for renderFile().

内容的提问来源于stack exchange,提问作者Emilio

火山引擎 最新活动