如何通过JavaScript中的服务器向用户显示消息(Node.Js)

时间:2017-11-02 19:08:34

标签: javascript node.js express

我有一个小问题。希望您能够帮助我。 我在NodeJs写了一个天气程序。当一个人想要搜索他们城市的天气时。他们可以在这里搜索,应用程序会向他们显示一条消息。那是我的问题。我可以从用户那里获取输入,我可以在命令行中看到该输入。这是代码:

app.post('/', function(req,res){
res.render('index');
console.log(req.body.city);
});      

这是代码的另一部分,但我无法向用户显示消息:

app.post('/', function (req, res) {
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.ejs', { weather: weatherText, error: null });
        }
    }
});

});

app.listen(7000, function(){
    console.log("Hello Boss \nserver is up at port => 7000");

});

注意:我有一个API密钥用于此目的。

1 个答案:

答案 0 :(得分:0)

尝试将两部分结合起来:

app.post('/', function (req, res) {
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.ejs', { weather: weatherText, error: null });
        }
    }
});

});

app.listen(7000, function(){
    console.log("Hello Boss \nserver is up at port => 7000");

});

Express.js每个URL /请求只能处理一个函数。如果你想让它们都运行,你必须将它们组合起来。