How can I add innerHTML in an ejs file?

I have this code:

const express = require('express')
const request = require('superagent');
const app = express()
const port = 3000

function advice() {

request
.get('http://api.adviceslip.com/advice')
.end((err, res) => {
    if (!err && res.status === 200) {
        try {
            JSON.parse(res.text)
        } catch (e) {
            return message.reply(', an api error occurred.');
        }
        const advice = JSON.parse(res.text)
        console.log(advice.slip.advice)
    } else {
    console.error(`REST call failed: ${err}, status code: ${res.status}`)
    }
});
}


app.set('view engine', 'ejs'); //Main endpoint, so http://localhost:3000
app.get('/', function(req, res){ 
  res.render('index',{users : [
            { name: advice() + " Is your advice.." },
  ]});
});

app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`)
});

And whenever I load the page, I want the advice to show up on the page but for right now, it’s just console.logging it.

My ejs file:

<html>
  <!DOCTYPE html>

  <head>
      <title>Twintails🎀 Bot - Info</title>
      <link rel="shortcut icon" href="https://i.imgur.com/NgV0KSf.png">
      <style>
          *,
          html {
              margin: 0;
              padding: 0;
              border: 0;
          }
  
          html {
              width: 100%;
              height: 100%;
          }
  
          body {
              width: 100%;
              height: 100%;
              position: relative;
              background-color: rgb(236, 152, 42);
          }
  
          .center {
              width: 100%;
              height: 50%;
              margin: 0;
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              color: white;
              font-family: "Trebuchet MS", Helvetica, sans-serif;
              text-align: center;
          }
  
          ul {
              font-size: 100px;
              margin-top: 200px;
          }
  
          p {
              font-size: 64px;
          }
  
          a:link {
    text-decoration: none;
  }
  
  a:visited {
    text-decoration: none;
  }
  
  a:hover {
    text-decoration: none;
  }
  
  a:active {
    text-decoration: none;
  }
  
      </style>
      <style>
  
  @import url('https://fonts.googleapis.com/css?family=Amatic+SC');
  
  body {
    margin: 0;
    height: 100%;
    background-image: linear-gradient(to top,#df43ab 0%, rgb(17, 194, 218) 100%);
    background-repeat: no-repeat;
    background-size: cover;
    background-attachment: fixed;
  }
  
  .button_container {
    position: absolute;
    left: 0;
    right: 0;
    top: 30%;
  }
  
  .description, .link {
    font-family: 'Amatic SC', cursive;
    text-align: center;
  }
  
  .description {
    font-size: 35px;
  }
  
  .btn {
    border: none;
    display: block;
    text-align: center;
    cursor: pointer;
    text-transform: uppercase;
    outline: none;
    overflow: hidden;
    position: relative;
    color: #fff;
    font-weight: 700;
    font-size: 15px;
    background-color: #222;
    padding: 17px 60px;
    margin: 0 auto;
    box-shadow: 0 5px 15px rgba(0,0,0,0.20);
  }
  
  .btn span {
    position: relative; 
    z-index: 1;
  }
  
  .btn:after {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    height: 490%;
    width: 140%;
    background: #78c7d2;
    -webkit-transition: all .5s ease-in-out;
    transition: all .5s ease-in-out;
    -webkit-transform: translateX(-98%) translateY(-25%) rotate(45deg);
    transform: translateX(-98%) translateY(-25%) rotate(45deg);
  }
  
  .btn:hover:after {
    -webkit-transform: translateX(-9%) translateY(-25%) rotate(45deg);
    transform: translateX(-9%) translateY(-25%) rotate(45deg);
  }
  
  .link {
    font-size: 20px;
    margin-top: 30px;
  }
  
  .link a {
    color: #000;
    font-size: 25px; 
  }
  
  
          </style>
  </head>
  
  <script>
    function goBack() {
      window.history.back();
    }
    </script>
  
  <body>
      <div class="center">
        <ul id="users">
          <% users.forEach(function(user){ %>
            <%= user.name %>
          <% })%>
        </ul>
      </div>
      <div class="button_container">
  
          <a onclick="goBack()"><button class="btn"><span>Go Back</span></button></a>
        </p>
      </div>
  </body>
  
  </html>
</html>

Whenever I reload the page, I get the advice in console but it says undefined on the page.

I think it has to do with you not using

return [result to return here];

? at the end of the function

How would I add that?

const express = require('express')
const request = require('superagent');
const app = express()
const port = 3000

function advice() {

request
.get('http://api.adviceslip.com/advice')
.end((err, res) => {
    if (!err && res.status === 200) {
        try {
            JSON.parse(res.text)
        } catch (e) {
            return message.reply(', an api error occurred.');
        }
        const advice = JSON.parse(res.text)
        return advice.slip.advice;
    } else {
    console.error(`REST call failed: ${err}, status code: ${res.status}`)
    }
});
}


app.set('view engine', 'ejs'); //Main endpoint, so http://localhost:3000
app.get('/', function(req, res){ 
  res.render('index',{users : [
            { name: advice() + " Is your advice.." },
  ]});
});

app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`)
});

Untested code^

I want to display the actual quote tho…

Try again I made some changes

Still says undefined

Maybe we can get someone who knows ejs to answer because I have never used ejs ever

1 Like

Fixed by doing:

const express = require('express')
const request = require('superagent');
const app = express()
const port = 3000

function txtadvice() {

    request
        .get('http://api.adviceslip.com/advice')
        .end((err, res) => {
            if (!err && res.status === 200) {
                try {
                    JSON.parse(res.text)
                } catch (e) {
                    return console.log("An API error occurred")
                }
                const advice = JSON.parse(res.text)
                console.log(advice.slip.advice)
                app.set('view engine', 'ejs'); //Main endpoint, so http://localhost:3000
                app.get('/', function (req, res) {
                    res.render('index', {
                        users: [{
                            name: `"${advice.slip.advice}",` + " Is your advice.."
                        }, ]
                    });
                });
            } else {
                console.error(`REST call failed: ${err}, status code: ${res.status}`)
            }
        });
}

txtadvice()


app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`)
});

Hello,

Next time, please try consulting a search engine first. Many people have probably asked the same question somewhere else.

1 Like

haha oof, I see the problem now:

{
  "slip": {
    "id": 168,
    "advice": "Do a bit more for your friends."
  }
}

the advice is contained in the slip object. Interesting… I thought you would have to use [slip][id]