【问题标题】:how to render Rest api JSON data to the HTML page using Node.js without using jquery如何在不使用 jquery 的情况下使用 Node.js 将 Rest api JSON 数据呈现到 HTML 页面
【发布时间】:2018-02-07 10:50:36
【问题描述】:

我正在尝试为 JSON 数据使用 RESTful API 并尝试在 HTML 页面上显示它。 这是将 API 解析为 JSON 数据的代码。

var https = require('https');
var schema;
var optionsget = {
    host : 'host name', // here only the domain name
    port : 443,
    path : 'your url', // the rest of the url with parameters if needed
    method : 'GET' // do GET
};
var reqGet = https.request(optionsget, function(res) {
    console.log("statusCode: ", res.statusCode);
       var chunks = [];
        res.on('data', function(data) {
            chunks.push(data);
        }).on('end', function() {
            var data   = Buffer.concat(chunks);
            schema = JSON.parse(data);
            console.log(schema);
        });

  });
        reqGet.end();
        reqGet.on('error', function(e) {
            console.error(e);
        });
var express = require('express');
var app = express();
app.get('/getData', function (request, response) {
        //console.log( data );
        response.end(schema);
        })

var server = app.listen(8081, function () {
 var host = server.address().address
 var port = server.address().port
 console.log("Example app listening at http://%s:%s", host, port)
})

我能够获取 JSON 格式的数据,但如何在 HTML 页面中显示?我正在尝试使用节点 js 来完成它,因为我不想为此使用 jquery。任何帮助将不胜感激。谢谢

【问题讨论】:

标签: html json node.js rest api


【解决方案1】:

你的 json 可以通过 ejs 渲染

npm i ejs

     var app = express();
            app.set('view engine', 'ejs');
            app.use(express.static(__dirname+'/public'));

            app.get('/view/getData', function (request, response) {
             //here view/getData is getData.ejs file in the view folder
             response.render(__dirname+'/public/view/getData'',{schema: schema});
    //schema is the object wich reference through the view in ejs template                    
});

你的视图文件在这里 getData.ejs

//将你的getData存储在view/getData.ejs中

<h>  <%= schema[0]%> </h>//your json data here 

basic ejs reference here

res.render brief explanation here

【讨论】:

    猜你喜欢
    • 2020-02-21
    • 1970-01-01
    • 2019-04-10
    • 2018-05-24
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多