简体   繁体   中英

Cannot display data from API request in views

I am brand new to Express and Node.js, trying to build server-rendered app which will display some data from API.

This is my code

app.js

 var express = require("express"); var app = express(); var request = require("request"); var apiKey = '****************************'; var bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.set('viewEngine', 'ejs'); const options = { method: 'POST', url: 'http://api.somethingsomething.com/content/search/v1?', headers: { 'X-Api-Key': `${apiKey}`, 'Content-Type': 'application/json' }, body: { 'queryString': 'pigs', 'resultContext' : { 'aspects' :['title','lifecycle','location','summary','editorial' ] } }, json: true } app.get('/', function(req, res) { request(options, function(error, response, body) { if (!error && response.statusCode == 200) { var info = JSON.stringify(body); console.log(info); res.render('index', { results: info}); // this does not render anything } }) }); app.listen(3000, function() { console.log("Listening on port 3000"); }) 

index.ejs

 <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <div id="searchResults"> <%= results %> </div> </body> </html> 

It does not render index.ejs and cannot display data. Error: No default engine was specified and no extension was provided. I tried googling it, but no luck. Any help will be appreciated; Thank you

problem was simple app.set('viewEngine', 'ejs'); was wrong, should be pp.set('view engine', 'ejs');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM