【问题标题】:How can I access my node data in ejs如何在 ejs 中访问我的节点数据
【发布时间】:2016-05-24 17:50:13
【问题描述】:

我有一个从 nedb 数据库获取数据的节点 Web 服务器。我想将此数据传递给我页面上的一些 ejs 代码,但节点死了并告诉我我传递的 JSON 对象中没有数据。这是服务器代码:

"use strict";

const DATA_HANDLER = require('./node/DataHandler');

class app {
     constructor() {
          this.ejsData = null;
          this.loadServer();
     }

     loadServer() {
          const HTTP = require('http'),
               EJS = require('ejs'),
               PORT = 1337,
               SERVER = HTTP.createServer((req, res) => {
                    let httpHandler = (err, str, contentType) => {
                         if (err) {
                              res.writeHead(500, { 'Content-Type': 'text/plain' });
                              res.end('An error has occurred: ' + err.message);
                         } else if (contentType.indexOf('image') >= 0) {
                              res.writeHead(200, { 'Content-Type': contentType });
                              res.end(str, 'binary');
                         } else {
                              res.writeHead(200, { 'Content-Type': contentType });
                              res.end(EJS.render(str, {
                                   data: this.ejsData,
                                   filename: 'index.ejs'
                              }));
                         }
                    };

                    if (req.method == 'POST') {
                         if (req.headers['x-requested-with'] === 'XMLHttpRequest') {
                              this.loadData(req, res, 0);
                         } else if (req.headers['x-requested-load'] === 'XMLHttpRequest1') {
                              this.loadData(req, res, 1);
                         } else {
                              console.log("[405] " + req.method + " to " + req.url);
                              res.writeHead(405, "Method not supported", { 'Content-Type': 'text/html' });
                              res.end('<html><head><title>405 - Method not supported</title></head><body><h1>Method not supported.</h1></body></html>');
                         }
                    } else if (req.url.indexOf('/javascripts/') >= 0) {
                         this.render(req.url.slice(1), 'application/ecmascript', httpHandler, 'utf-8');
                    } else if (req.url.indexOf('/css/') >= 0) {
                         this.render(req.url.slice(1), 'text/css', httpHandler, 'utf-8');
                    } else if (req.url.indexOf('/images/') >= 0) {
                         this.render(req.url.slice(1), 'image/jpeg', httpHandler, 'binary');
                    } else {
                         this.render('public/views/index.ejs', 'text/html', httpHandler, 'utf-8');
                    }
               }).listen(PORT, _ => console.log('-= Work Order Server Listening at http://127.0.0.1:' + PORT + ' =-'));
     }

     render(path, contentType, callback, encoding) {
          const FS = require('fs');
        FS.readFile(__dirname + '/' + path, encoding ? encoding : 'utf-8', (err, str) => { // ternary
            callback(err, str, contentType);
        });
     }

     loadData(req, res, whichAjax) {
          if (whichAjax === 1) {
               const FORMIDABLE = require('formidable');
               let formData = {};
               new FORMIDABLE.IncomingForm().parse(req).on('field', (field, name) => {
                    formData[field] = name;
               }).on('error', (err) => {
                    next(err);
               }).on('end', () => {
                    new DATA_HANDLER().queryData(formData);
               });
          }
          new DATA_HANDLER().loadData((docs) => {
               let jsonDocs = JSON.stringify(docs);
               res.writeHead(200, {'content-type': 'application/json'});
               res.end(jsonDocs);
               this.setEjsData(docs);
          });
     }

     setEjsData(docs) {
          this.ejsData = docs;
     }
}

module.exports = app;

这是我的 ejs 页面:

<div class="row">
    <div class="small-12 columns">
        <table>
            <% if (data) { %>
                <% for (let i = 0; i < data.length; i++) { %>
                    <tr>
                        <td><%= data.building %></td>
                        <td><%= data.roomNumber %></td>
                        <td><%= data.problemDesc %></td>
                        <td><%= data.assigned %></td>
                        <td><%= data.status %></td>
                    </tr>
                <% } %>
            <% } %>
        </table>
    </div>
</div>

错误是 data.length 为空。我添加了 if (data) 块来停止错误。我没有使用任何框架(Express 或 Koa)。

【问题讨论】:

    标签: node.js ejs


    【解决方案1】:

    尝试在您的 ejs 模板中使用 ejsData 而不是 data

    【讨论】:

    • 这是部分正确的。请在下面查看我的解决方案。
    【解决方案2】:

    以下是上述问题中解决问题的几行:

    app.js

    else if (contentType.indexOf('html') >= 0) {
         res.writeHead(200, { 'Content-Type': contentType });
         res.end(EJS.render(str, {
              data: this.ejsData,
              filename: 'index.ejs' }));
     }
    

    ejs 文件:

    <% for (let i = 0; i < data.length; i++) { %>
         <tr>
              <td><%= data[i].date %></td>
              <td><%= data[i].building %></td>
              <td><%= data[i].roomNumber %></td>
              <td><%= data[i].problemDesc %></td>
              <td><%= data[i].assigned %></td>
              <td><%= data[i].status %></td>
         </tr>
    <% } %>
    

    【讨论】:

      猜你喜欢
      • 2017-12-29
      • 2020-12-12
      • 2019-10-11
      • 1970-01-01
      • 2023-03-29
      • 2017-11-07
      • 2019-02-13
      • 1970-01-01
      • 2015-08-11
      相关资源
      最近更新 更多