将数据从data.json文件(expressJS)解析为index.ejs

时间:2019-12-06 13:13:43

标签: javascript node.js json express

我正在尝试从data.json文件中解析数据,我想将网站的所有数据存储在此json文件中,然后将数据解析至index.ejs文件。下面是我的index.ejs文件,app.js(用于设置的文件)和data.json文件的代码段。

HTML代码段(index.ejs)

<ul class="menu-list">
    <li><%= data.menu.title %></li>
</ul>

Json文件(data.json)

{
 "data": {
    "menu": [
        {
            "title": "Home",
            "link": ""
        },
        {
            "title": "Contact",
            "link": ""
        }
     ]
  }
}

设置文件(app.js)

  var createError = require('http-errors');
  var express = require('express');
  var path = require('path');
  var cookieParser = require('cookie-parser');
  var logger = require('morgan');
  var sassMiddleware = require('node-sass-middleware');

  var indexRouter = require('./routes/index');
  var usersRouter = require('./routes/users');

  var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// compiling sass files
app.use(sassMiddleware({
 src: path.join(__dirname, 'public/stylesheets/scss'),
 dest: path.join(__dirname, 'public/stylesheets'),
 debug: true,
 outputStyle: 'compressed',
 prefix: '/stylesheets'
}));

app.use('/public', express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
 next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
 // set locals, only providing error in development
 res.locals.message = err.message;
 res.locals.error = req.app.get('env') === 'development' ? err : {};

 // render the error page
 res.status(err.status || 500);
 res.render('error');
});


module.exports = app;

原谅我的缩进-怪异的。所有文件都处于同一级别。

1 个答案:

答案 0 :(得分:0)

在您的示例中,将<li><%= data.menu.title %></li>替换为<li><%= data.menu[0].title %></li>,因为菜单不是数组数据 样本数据

var data = 
     {"data": {
        "menu": [
            {
                "title": "Home",
                "link": ""
            },
            {
                "title": "Contact",
                "link": ""
            }
         ]
      } };

Ejs代码

 <ul class="menu-list">



<% for(var i=0; i < data.data.menu.length; i++) { %>

    <li><%= data.data.menu[i].title %></li>

<% } %>

  </ul>