Reputation: 235
I'm trying to do get request and get data from URL. I use an Express framework. Before I've used only Node JS and all was OK. But people from stack recommend me to use express.
So, I try to run app and render data from url to my ejs
page.
But I got Cannot GET /
Please, can you help me with my mistake?
My app.js code:
var express = require('express');
var router = express.Router();
var http = require('http');
var path = require('path');
var config = require('config');
var log = require('libs/log')(module);
var request = require('request');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var url = 'http://public.api.openprocurement.org/api/2.4/tenders?offset=2018-01-05T21:02:46.167030+02:00';
var app = express();
app.set('port', config.get('port'));
app.engine('ejs', require('ejs-locals'));
app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', router);
router.get('/', function(req, res, next) {
request('http://public.api.openprocurement.org/api/2.4/tenders?offset=2018-01-05T21:02:46.167030+02:00', function (err, response, body) {
if (err || response.statusCode !== 200) {
return res.sendStatus(500);
}
res.render('index', { title : 'Main page', news : JSON.parse(body), some: '<b>Hello</b>' });
});
});
// app.get('/', function (req, res, next) {
// res.render("index", {
// body: '<b>Hello</b>'
// });
// });
app.use(function (err, req, res, next) {
if(app.get('env') == 'development') {
var errorHandler = express.errorHandler();
errorHandler(err, req, res, next);
} else {
res.send(500);
}
});
http.createServer(app).listen(config.get('port'), function() {
log.info('Express server listening on port ' + config.get('port'));
});
module.exports = app;
And my small ejs file:
<%-news%>
<%-some%>
On the screenshot is the JSON which I want to display on the page.
Upvotes: 0
Views: 1140
Reputation: 1748
news
contains three props, next_page
, data
, and prev_page
. If you want to access the contents of data
you will need to loop through it as it is an array
:
<% if (news.data) { %>
<% news.data.forEach(function(obj){ %>
<span><%= obj.id %></span>
<% }); %>
<% } %>
It can be a little tricky sometimes to keep track of ejs
syntax. There are a lot of npm
modules that you can check out if the standard error messages are hard to read.
Upvotes: 2