如何以节点js显示从数据库中获取的json数据??没有json格式

时间:2019-03-22 12:13:56

标签: javascript node.js json nodes node-modules

这是我的代码。

var http=require("http");
var fs = require("fs");
var express = require("express");
var app = express();
var path = require("path");
var mysql = require('mysql');
var ejs = require("ejs")
var bodyParser = require('body-parser');
app.set('view engine' , 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "testn"
});

con.connect(function(err) {
    if (err) throw err;
    con.query("SELECT * FROM form", function (err, result, fields) {
      if (err) throw err;
      console.log(JSON.stringify(result));
      app.get('/', function(req, res) {
        res.render('index',{data:JSON.stringify(result)});
      
      });

    });
  });

app.listen(3010);
console.log("Running at Port 3010");

这是我的html

<!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>Document</title>
</head>
<body>
    <header>
        <div class="container">
            <p><%=data%><p>
             
        </div>
    </header>
</body>
</html>

这是我的输出

[{“ name”:“ Prakash”,“ email”:“ prakashvpsm@gmail.com”,“ description”:“ uykiukjk”},{“ name”:“ Mathan”,“ email”:“ v。 prakash.av@gmail.com“,”描述“:” uykiukjk“},{”名称“:” prakashvpsm“,”电子邮件“:” prakash@123.com“,”描述“:” uykiukjk“},{”名称”:“ Prakash”,“电子邮件”:“ qdw@fff.com”,“描述”:“ wddfwdpfk”},{“名称”:“ Prakash”,“电子邮件”:“ prakashvpsm@gmail.com”,” description“:” uykiukjk“}]

但是我不想要json格式。我想要没有数据。数据是从本地服务器获取的

1 个答案:

答案 0 :(得分:1)

我猜下面的解决方案是您想要的。

const express = require("express");
const app = express();
const mysql = require('mysql');
const bodyParser = require('body-parser');

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());

const con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "testn"
});

con.connect(function (err) {
    if (err) throw err;
});

app.get('/', function (req, res) {
    const result = con.query("SELECT * FROM form", function (err, result, fields) {
        if (err) throw err;
        return results;
    });
    res.render('index', {
        data: results
    });
});


app.listen(3010);
console.log("Running at Port 3010");

ejs模板

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

<body>
    <div >
        <table>
            <% for(const row of data) { %>
            <tr>
                <td>
                    <%= row.name %>
                </td>
                <td>
                    <%= row.email %>
                </td>
                <td>
                    <%= row.description %>
                </td>
            </tr>
            <% } %>
        </table>
    </div>
</body>

</html>