无法将json发送到html并导致<%-正常工作

时间:2019-07-10 14:09:18

标签: json express ejs

因此,我尝试使用json文件中的值显示在网页上。例如,一个值就是手风琴按钮上的文本。

我正在使用express和ejs,并且我一直试图使用<%-%>来调用json文件中的文本,但它似乎不会出现在网页上。

index.js

struct book *

webpage.ejs

    app.set('view engine', 'ejs');
    app.engine('html', require('ejs').renderFile);

app.get('/', function(req, res) {
     res.locals.ClinNotes1=('.\ClinNotes.json');
     res.render('webpage');
     })

ClinNotes.json

<div id="Problems" class="tabcontent">
    <div class="problemItems">
    <button class="accordion" id="accordionDis">
    <span><ul><%-ClinNotes1.resourceType%></ul></span>

2 个答案:

答案 0 :(得分:1)

如果要在网页上显示 JSON 数据,可以执行以下操作:

index.js

const http = require('http')
const fs = require('fs');
const qs = require('querystring');
const path = require('path')
const static = require('node-static');
const internalIp = require('ip');
var template = require('./lib/template.js');
var file = new static.Server(__dirname);


const server = http.createServer((req, res) => {

  // Dont know why it causes occasional 404...
  file.serve(req, res);

  var myLocaIP = internalIp.address();
  if (req.url === '/') {
    let filePath = path.join(__dirname, '/', req.url);
    let extname = path.extname(filePath);
    let contentType = 'text/html';
    switch (extname) {
      case '.js':
        contentType = 'text/javascript';
        break;
      case 'css':
        contentType = 'text/css';
        break;
      case '.json':
        contentType = 'application/json';
        break;
      case '.jpg':
        contentType = 'image/png';
        break;
      case '.js':
        contentType = 'image/jpg';
        break;
      }

    // ============== Add Note Box ==========================================
    fs.readFile(path.join(__dirname, 'data', 'note_txt.txt'), (err, data) => {
     notetxt=String(data);
    });


    // ============== create LISTs from JSON ==========================================

    fs.readFile(path.join(__dirname, 'data', 'url_list.json'), (err, data) => {
      if (err) {
        console.error('There was an error reading the file!', err);
        console.log(error.code);
      }
      var list_a = '';
      var list_b = '';
      var list_c = '';
      var list_d = '';

      var obj = JSON.parse(data);

      list_a = appendItem(obj, 'listA', list_a);
      list_b = appendItem(obj, 'listB', list_b);
      list_c = appendItem(obj, 'listC', list_c);
      list_d = appendItem(obj, 'listD', list_d);

      var html = template.html(list_a, list_b, list_c, list_d, notetxt, myLocaIP);
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(html, 'utf-8');
    });
  }

webpage.ejs

//here import your json file

const notes = require('./ClinNotes.json'); //suppose your file is in the root directory

app.get('/', function(req, res) {
     res.render('webpage', {data: notes});
 })

希望对您有帮助

答案 1 :(得分:0)

这是我整理的一个简单示例。

基本上,您希望以与Javascript对象相同的方式遍历JSON文件。

app.js

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

//Use EJS Templating Engine
app.set('view engine', 'ejs');

app.get('/', (req, res, next) => {
  res.locals.dataFromJSON = require('./data.json');
  res.render('index');
});

//Start Server
app.listen(port, () => {
  console.log(`Server started on port number ${port}`);
});

index.ejs

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Example</title>
</head>

<body>
  <h1>Hope this helps!</h1>
  <% Object.values(dataFromJSON).forEach((value) => { %>
  <button><%= value %></button>
  <% }); %>
</body>

</html>

data.json

{
  "resourceType": "Bundle",
  "resourceType2": "Bundle2",
  "resourceType3": "Bundle3",
  "resourceType4": "Bundle4"
}

Here is a gitub repo i created

Here is the expected output deployed to heroku

我希望这会有所帮助! ?