ethelake
ethelake

Reputation: 57

accessing JSON through javascript in ejs file

Hello I would like to get any help to get through this issue with my code.

so this is my server file with node js

//setup

var express = require("express");
var request = require("request");
var bodyParser = require("body-parser");
var app = express();

//make body-parser workin
app.use(bodyParser.urlencoded({extended: true}));
//help excluding ejs extension
app.set("view engine", "ejs");
//pointing express to look at public folders for css files. 
app.use(express.static("public"));


//routing starts
//root directory
app.get("/", function(req, res){
   res.render("home", { data : "" });
});

app.post("/results", function(req, res){
    var mname = req.body.movieName;
    var myear = req.body.movieYear;
    var url = "http://www.omdbapi.com/?s="+mname+"&y="+myear+"&apikey=$$$$$$$$$$$$";
    request(url, function(error, response, body){
    if(!error && response.statusCode == 200){
       var data = JSON.parse(body);
       res.render("home", { data : data });
       console.log(url);
    }else{
      console.log("ERRRORRRR WARNNNINNNNNNGG");
      console.log(error);
    }

    });

and this is part of my ejs file that want to access the JSON retrieved from API request

<%= data["Search"][0] %>

However, I get error like this

==================================================================== TypeError: /home/ubuntu/workspace/MovieSearchApp/views/home.ejs:32

32| <%= data["Search"][0] %>

Cannot read property '0' of undefined
at eval (eval at compile (/home/ubuntu/workspace/MovieSearchApp node_modules/ejs/lib/ejs.js:549:12), <anonymous>:11:40) 

etc

====================================================================

so I am assuming my way to access the JSON is somehow wrong so I looked at my JSON in detail json example

and I went back to my ejs file and tried

<%= data["Search"] %>

it gives me no error and shows up as

[object Object]

could somebody give me some direction to how to access this JSON correctly?

thanks for your time and help in advance

Upvotes: 2

Views: 1172

Answers (1)

Molda
Molda

Reputation: 5704

The most obvious issue is that you are passing data: "" in app.get("/",..

This means that when you go to your website's root / the data is a empty string.

Change it to

app.get("/", function(req, res){
   res.render("home");
});

and in the view check if data exists

<% if (data) { %>

<% } else { %>

<% } %>

Upvotes: 2

Related Questions