1

I would like to know how to pass variables in Node.js

When I try to fetch and pass some variables to ejs,error something like below has occured.

    27|                 <div id="content">
 >> 29|                 <%=json%>
    30|                 </div>
json is not defined

My current work is like below. Are there any problem? If somone has opinion,please let me know. Thanks

const fetch = require("node-fetch");
const express = require("express");
const app = express();

const API_KEY="https://opentdb.com/api.php?amount=1&type=multiple";


app.get('/', (req, res) => {
  fetch(API_KEY)
      .then(response => response.json())
      .then(json => {
       console.log(json);    
       res.render("quiz.ejs", json);
    
      });
});

app.listen(8080,()=>{
    console.log('server is running!');
});
              <div id="content">
                  <%= json %>
                </div>

2 Answers 2

1

Here, is how you can do it

app.get('/', (req, res) => {
   fetch(API_KEY)
      .then(response => response.json())
      .then(json => {
         console.log(json);
         res.render("quiz.ejs", {
            json: json
         });
      });
});

so, to print an object to the template (ejs) we first need to stringify it:

<%= JSON.stringify(json)%> 
Sign up to request clarification or add additional context in comments.

Comments

0

On the rendering section of your code. Try sending second argument inside the curly braces as like

res.render('quiz.ejs', {json});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.