c_anirudh
c_anirudh

Reputation: 394

Reference error when using ejs with express

I am making a simple weather application using express and passing the weather info I get from my API to the html file, where I am using ejs to display them.

Here is the file for creating the server:

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

const apiKey = "*******************";

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "ejs");

app.get("/", function (req, res) {
    res.render("index", { weather: null, error: null });
});

app.post("/", function (req, res) {
    res.render("index");
    console.log(req.body.city);
    let city = req.body.city;
    let url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&appid=${apiKey}`;
    request(url, function (err, response, body) {
        if (err) {
            res.render('index', { weather: null, error: 'Error, please try again' });
        } else {
            let weather = JSON.parse(body);
            if (weather.main == undefined) {
                res.render('index', { weather: null, error: 'Error, please try again' });
            } else {
                let weatherText = `It's ${weather.main.temp} degrees in ${weather.name}!`;
                res.render('index', { weather: weatherText, error: null });
            }
        }
    });
});

app.listen(8080, function () {
    console.log("Example app listening on port 8080 !");
});

and here is my html file with ejs :

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="/css/style.css" />
</head>

<body>
    <h1>Know Your Weather ! </h1>
    <div class="container">
        <fieldset>
            <form action="/" method="POST">
                <input name="city" type="text" class="ghost-input" placeholder="Enter a City" required>
                <input type="submit" class="ghost-button" value="Get Weather">
            </form>
            <% if(weather !== null){ %> <p><%= weather %></p><% } %>
            <% if(error !== null){ %> <p><%= error %></p><% } %>
        </fieldset>
    </div>

</body>

</html>

But when I give an input in the website, I get the following error:

> ReferenceError: /home/anirudh/Desktop/weather-app/views/index.ejs:20
>     18|                 <input type="submit" class="ghost-button" value="Get Weather">
>     19|             </form>
>  >> 20|             <% if(weather !== null){ %> <p><%= weather %></p><% } %>
>     21|             <% if(error !== null){ %> <p><%= error %></p><% } %>
>     22|         </fieldset>
>     23|     </div>
> 
> weather is not defined
>     at eval (eval at compile (/home/anirudh/Desktop/weather-app/node_modules/ejs/lib/ejs.js:618:12),
> <anonymous>:11:8)
>     at returnedFn (/home/anirudh/Desktop/weather-app/node_modules/ejs/lib/ejs.js:653:17)
>     at tryHandleCache (/home/anirudh/Desktop/weather-app/node_modules/ejs/lib/ejs.js:251:36)
>     at View.exports.renderFile [as engine] (/home/anirudh/Desktop/weather-app/node_modules/ejs/lib/ejs.js:482:10)
>     at View.render (/home/anirudh/Desktop/weather-app/node_modules/express/lib/view.js:135:8)
>     at tryRender (/home/anirudh/Desktop/weather-app/node_modules/express/lib/application.js:640:10)
>     at Function.render (/home/anirudh/Desktop/weather-app/node_modules/express/lib/application.js:592:3)
>     at ServerResponse.render (/home/anirudh/Desktop/weather-app/node_modules/express/lib/response.js:1008:7)
>     at /home/anirudh/Desktop/weather-app/server.js:17:9
>     at Layer.handle [as handle_request] (/home/anirudh/Desktop/weather-app/node_modules/express/lib/router/layer.js:95:5)

What am I doing wrong with the ejs?

Upvotes: 2

Views: 2786

Answers (1)

Golo Roden
Golo Roden

Reputation: 150982

The problem is in the post route you define:

app.post("/", function (req, res) {
  res.render("index");
  // ...

This call to res.render does not provide any locals, and hence, weather is not defined. I haven't tried it, but this immediately caught my eye, and I am pretty sure that this is the source of the error you encounter – especially since you said that it only happens when you submit data.

I assume that this is an unintended leftover of a previous version or some debugging, since you correctly render a few lines below. If you simply remove this call to res.render, I guess that things should work as expected.

Upvotes: 1

Related Questions