在Express中使用ejs时出现参考错误

时间:2019-02-13 13:20:50

标签: node.js express ejs

我正在使用express开发一个简单的天气应用程序,并将从API中获取的天气信息传递到html文件中,在此我使用ejs来显示它们。

这是用于创建服务器的文件:

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 !");
});

这是我的带ejs的html文件:

<!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>

但是当我在网站上输入内容时,出现以下错误:

> 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)

我的ejs怎么了?

1 个答案:

答案 0 :(得分:1)

问题出在您定义的post路线中:

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

此对res.render的调用未提供任何本地信息,因此未定义weather。我没有尝试过,但是这立即引起了我的注意,我可以肯定这是您遇到的错误的根源-特别是因为您说过仅在提交数据时才会发生。

我认为这是以前版本的意外残留或一些调试,因为您正确地渲染了以下几行。如果您仅删除对res.render的调用,我想事情应该会按预期进行。