Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当数据可以';无法从get请求中提取_Javascript_Jquery_Node.js - Fatal编程技术网

Javascript 当数据可以';无法从get请求中提取

Javascript 当数据可以';无法从get请求中提取,javascript,jquery,node.js,Javascript,Jquery,Node.js,当用户键入城市名称时,此应用程序会获取当前天气,或者它可以使用您的IP地址获取您的当前位置和当前天气 问题是:当用户在一个不存在的城市中键入诸如“jklsaffbhjbdsfjhbf”之类的内容时,故障消息会按预期淡入,但随后服务器会关闭,用户无法在终端中重新启动服务器之前发出任何天气请求 我认为问题存在于我在文件weather.js中承诺的某个地方,或者可能存在于我在weatherFetcher.js中处理前端get请求的方式,或者在app.js中处理后端get请求的方式 var expres

当用户键入城市名称时,此应用程序会获取当前天气,或者它可以使用您的IP地址获取您的当前位置和当前天气

问题是:当用户在一个不存在的城市中键入诸如“jklsaffbhjbdsfjhbf”之类的内容时,故障消息会按预期淡入,但随后服务器会关闭,用户无法在终端中重新启动服务器之前发出任何天气请求

我认为问题存在于我在文件weather.js中承诺的某个地方,或者可能存在于我在weatherFetcher.js中处理前端get请求的方式,或者在app.js中处理后端get请求的方式

var express = require('express');
var weather = require('./public/js/weather.js');
var location = require('./public/js/location.js');
var app = express();
var PORT = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
    res.send(__dirname + '/public/index.html');
});
app.listen(PORT, function() {
    console.log('Express Server Started on port ' + PORT);
});
app.get('/location', function(req, res) {
    var city = req.query.city;
    weather(city).then(function (currentWeather) {
        res.json(currentWeather);
    });
});
app.get('/guessweather', function(req, res) {
    location().then(function (guessedLocation) {
        weather(guessedLocation).then(function (guessedWeather) {
            res.json(guessedWeather);
        });
    });
});
var request = require('request');
module.exports = function (location) {
    return new Promise(function (resolve, reject) {
        var encodedLocation = encodeURIComponent(location);
        var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + encodedLocation + '&units=imperial&appid=2de143494c0b295cca9337e1e96b00e0';
        if (!location) {
            return reject('No location provided');
        }
        request({url: url, json: true}, function (error, response, body) {
            if (error) {
                return reject('Unable to fetch weather.');
            } else {
                return resolve('The current temperature in ' + body.name + ' is ' + body.main.temp + ' degrees farenheit with humidity at ' + body.main.humidity + '%.');
            }
        });
    });
};
var request = require('request');
module.exports = function () {
    return new Promise(function (resolve, reject) {
        var url = 'http://ipinfo.io';
        request({
            url: url,
            json: true
        }, function (error, response, body) {
            if (error) {
                return reject('Unable to fetch location.');
            } else {
                console.log(body.city);
                return resolve(body.city);
            }
        });
    });
}
$(document).ready(function() {
    $('#success').hide();
    $('#failure').hide();
    $('#noCity').hide();
    $('#findMyWeather').click(function(event) {
        $('#success').hide();
        $('#failure').hide();
        $('#noCity').hide();
        var $cityName = $('#city').val();
        if (typeof $cityName === 'string' && $cityName.length > 0) {
            $.get('/location?city=' + $cityName, function (data) {
            }).done(function (data) {
                $("#success").html(data).fadeIn();
                $("#success").prepend('<p id="cityTitle" class="lead">'+ $cityName +'</p>');
                $('#city').value = ""; //This doesn't seem to be working
            }).fail(function () {
                $("#failure").fadeIn();
            });
        } else {
            $("#noCity").fadeIn();
        }
    });
    $('#findLocalWeather').click(function(event) {
        $('#success').hide();
        $('#failure').hide();
        $('#noCity').hide();
        $.get('/guessweather', function (data) {
            if (data == "") {
                $("#failure").fadeIn();
            } else {
                $("#success").html(data).fadeIn();
            }
        });
    });
});
需要帮助修复此问题,以便服务器不会关闭,用户可以继续发出天气请求

app.js

var express = require('express');
var weather = require('./public/js/weather.js');
var location = require('./public/js/location.js');
var app = express();
var PORT = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
    res.send(__dirname + '/public/index.html');
});
app.listen(PORT, function() {
    console.log('Express Server Started on port ' + PORT);
});
app.get('/location', function(req, res) {
    var city = req.query.city;
    weather(city).then(function (currentWeather) {
        res.json(currentWeather);
    });
});
app.get('/guessweather', function(req, res) {
    location().then(function (guessedLocation) {
        weather(guessedLocation).then(function (guessedWeather) {
            res.json(guessedWeather);
        });
    });
});
var request = require('request');
module.exports = function (location) {
    return new Promise(function (resolve, reject) {
        var encodedLocation = encodeURIComponent(location);
        var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + encodedLocation + '&units=imperial&appid=2de143494c0b295cca9337e1e96b00e0';
        if (!location) {
            return reject('No location provided');
        }
        request({url: url, json: true}, function (error, response, body) {
            if (error) {
                return reject('Unable to fetch weather.');
            } else {
                return resolve('The current temperature in ' + body.name + ' is ' + body.main.temp + ' degrees farenheit with humidity at ' + body.main.humidity + '%.');
            }
        });
    });
};
var request = require('request');
module.exports = function () {
    return new Promise(function (resolve, reject) {
        var url = 'http://ipinfo.io';
        request({
            url: url,
            json: true
        }, function (error, response, body) {
            if (error) {
                return reject('Unable to fetch location.');
            } else {
                console.log(body.city);
                return resolve(body.city);
            }
        });
    });
}
$(document).ready(function() {
    $('#success').hide();
    $('#failure').hide();
    $('#noCity').hide();
    $('#findMyWeather').click(function(event) {
        $('#success').hide();
        $('#failure').hide();
        $('#noCity').hide();
        var $cityName = $('#city').val();
        if (typeof $cityName === 'string' && $cityName.length > 0) {
            $.get('/location?city=' + $cityName, function (data) {
            }).done(function (data) {
                $("#success").html(data).fadeIn();
                $("#success").prepend('<p id="cityTitle" class="lead">'+ $cityName +'</p>');
                $('#city').value = ""; //This doesn't seem to be working
            }).fail(function () {
                $("#failure").fadeIn();
            });
        } else {
            $("#noCity").fadeIn();
        }
    });
    $('#findLocalWeather').click(function(event) {
        $('#success').hide();
        $('#failure').hide();
        $('#noCity').hide();
        $.get('/guessweather', function (data) {
            if (data == "") {
                $("#failure").fadeIn();
            } else {
                $("#success").html(data).fadeIn();
            }
        });
    });
});
weather.js

var express = require('express');
var weather = require('./public/js/weather.js');
var location = require('./public/js/location.js');
var app = express();
var PORT = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
    res.send(__dirname + '/public/index.html');
});
app.listen(PORT, function() {
    console.log('Express Server Started on port ' + PORT);
});
app.get('/location', function(req, res) {
    var city = req.query.city;
    weather(city).then(function (currentWeather) {
        res.json(currentWeather);
    });
});
app.get('/guessweather', function(req, res) {
    location().then(function (guessedLocation) {
        weather(guessedLocation).then(function (guessedWeather) {
            res.json(guessedWeather);
        });
    });
});
var request = require('request');
module.exports = function (location) {
    return new Promise(function (resolve, reject) {
        var encodedLocation = encodeURIComponent(location);
        var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + encodedLocation + '&units=imperial&appid=2de143494c0b295cca9337e1e96b00e0';
        if (!location) {
            return reject('No location provided');
        }
        request({url: url, json: true}, function (error, response, body) {
            if (error) {
                return reject('Unable to fetch weather.');
            } else {
                return resolve('The current temperature in ' + body.name + ' is ' + body.main.temp + ' degrees farenheit with humidity at ' + body.main.humidity + '%.');
            }
        });
    });
};
var request = require('request');
module.exports = function () {
    return new Promise(function (resolve, reject) {
        var url = 'http://ipinfo.io';
        request({
            url: url,
            json: true
        }, function (error, response, body) {
            if (error) {
                return reject('Unable to fetch location.');
            } else {
                console.log(body.city);
                return resolve(body.city);
            }
        });
    });
}
$(document).ready(function() {
    $('#success').hide();
    $('#failure').hide();
    $('#noCity').hide();
    $('#findMyWeather').click(function(event) {
        $('#success').hide();
        $('#failure').hide();
        $('#noCity').hide();
        var $cityName = $('#city').val();
        if (typeof $cityName === 'string' && $cityName.length > 0) {
            $.get('/location?city=' + $cityName, function (data) {
            }).done(function (data) {
                $("#success").html(data).fadeIn();
                $("#success").prepend('<p id="cityTitle" class="lead">'+ $cityName +'</p>');
                $('#city').value = ""; //This doesn't seem to be working
            }).fail(function () {
                $("#failure").fadeIn();
            });
        } else {
            $("#noCity").fadeIn();
        }
    });
    $('#findLocalWeather').click(function(event) {
        $('#success').hide();
        $('#failure').hide();
        $('#noCity').hide();
        $.get('/guessweather', function (data) {
            if (data == "") {
                $("#failure").fadeIn();
            } else {
                $("#success").html(data).fadeIn();
            }
        });
    });
});
location.js

var express = require('express');
var weather = require('./public/js/weather.js');
var location = require('./public/js/location.js');
var app = express();
var PORT = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
    res.send(__dirname + '/public/index.html');
});
app.listen(PORT, function() {
    console.log('Express Server Started on port ' + PORT);
});
app.get('/location', function(req, res) {
    var city = req.query.city;
    weather(city).then(function (currentWeather) {
        res.json(currentWeather);
    });
});
app.get('/guessweather', function(req, res) {
    location().then(function (guessedLocation) {
        weather(guessedLocation).then(function (guessedWeather) {
            res.json(guessedWeather);
        });
    });
});
var request = require('request');
module.exports = function (location) {
    return new Promise(function (resolve, reject) {
        var encodedLocation = encodeURIComponent(location);
        var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + encodedLocation + '&units=imperial&appid=2de143494c0b295cca9337e1e96b00e0';
        if (!location) {
            return reject('No location provided');
        }
        request({url: url, json: true}, function (error, response, body) {
            if (error) {
                return reject('Unable to fetch weather.');
            } else {
                return resolve('The current temperature in ' + body.name + ' is ' + body.main.temp + ' degrees farenheit with humidity at ' + body.main.humidity + '%.');
            }
        });
    });
};
var request = require('request');
module.exports = function () {
    return new Promise(function (resolve, reject) {
        var url = 'http://ipinfo.io';
        request({
            url: url,
            json: true
        }, function (error, response, body) {
            if (error) {
                return reject('Unable to fetch location.');
            } else {
                console.log(body.city);
                return resolve(body.city);
            }
        });
    });
}
$(document).ready(function() {
    $('#success').hide();
    $('#failure').hide();
    $('#noCity').hide();
    $('#findMyWeather').click(function(event) {
        $('#success').hide();
        $('#failure').hide();
        $('#noCity').hide();
        var $cityName = $('#city').val();
        if (typeof $cityName === 'string' && $cityName.length > 0) {
            $.get('/location?city=' + $cityName, function (data) {
            }).done(function (data) {
                $("#success").html(data).fadeIn();
                $("#success").prepend('<p id="cityTitle" class="lead">'+ $cityName +'</p>');
                $('#city').value = ""; //This doesn't seem to be working
            }).fail(function () {
                $("#failure").fadeIn();
            });
        } else {
            $("#noCity").fadeIn();
        }
    });
    $('#findLocalWeather').click(function(event) {
        $('#success').hide();
        $('#failure').hide();
        $('#noCity').hide();
        $.get('/guessweather', function (data) {
            if (data == "") {
                $("#failure").fadeIn();
            } else {
                $("#success").html(data).fadeIn();
            }
        });
    });
});
weatherFetcher.js

var express = require('express');
var weather = require('./public/js/weather.js');
var location = require('./public/js/location.js');
var app = express();
var PORT = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
    res.send(__dirname + '/public/index.html');
});
app.listen(PORT, function() {
    console.log('Express Server Started on port ' + PORT);
});
app.get('/location', function(req, res) {
    var city = req.query.city;
    weather(city).then(function (currentWeather) {
        res.json(currentWeather);
    });
});
app.get('/guessweather', function(req, res) {
    location().then(function (guessedLocation) {
        weather(guessedLocation).then(function (guessedWeather) {
            res.json(guessedWeather);
        });
    });
});
var request = require('request');
module.exports = function (location) {
    return new Promise(function (resolve, reject) {
        var encodedLocation = encodeURIComponent(location);
        var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + encodedLocation + '&units=imperial&appid=2de143494c0b295cca9337e1e96b00e0';
        if (!location) {
            return reject('No location provided');
        }
        request({url: url, json: true}, function (error, response, body) {
            if (error) {
                return reject('Unable to fetch weather.');
            } else {
                return resolve('The current temperature in ' + body.name + ' is ' + body.main.temp + ' degrees farenheit with humidity at ' + body.main.humidity + '%.');
            }
        });
    });
};
var request = require('request');
module.exports = function () {
    return new Promise(function (resolve, reject) {
        var url = 'http://ipinfo.io';
        request({
            url: url,
            json: true
        }, function (error, response, body) {
            if (error) {
                return reject('Unable to fetch location.');
            } else {
                console.log(body.city);
                return resolve(body.city);
            }
        });
    });
}
$(document).ready(function() {
    $('#success').hide();
    $('#failure').hide();
    $('#noCity').hide();
    $('#findMyWeather').click(function(event) {
        $('#success').hide();
        $('#failure').hide();
        $('#noCity').hide();
        var $cityName = $('#city').val();
        if (typeof $cityName === 'string' && $cityName.length > 0) {
            $.get('/location?city=' + $cityName, function (data) {
            }).done(function (data) {
                $("#success").html(data).fadeIn();
                $("#success").prepend('<p id="cityTitle" class="lead">'+ $cityName +'</p>');
                $('#city').value = ""; //This doesn't seem to be working
            }).fail(function () {
                $("#failure").fadeIn();
            });
        } else {
            $("#noCity").fadeIn();
        }
    });
    $('#findLocalWeather').click(function(event) {
        $('#success').hide();
        $('#failure').hide();
        $('#noCity').hide();
        $.get('/guessweather', function (data) {
            if (data == "") {
                $("#failure").fadeIn();
            } else {
                $("#success").html(data).fadeIn();
            }
        });
    });
});
$(文档).ready(函数(){
$(“#成功”).hide();
$(“#失败”).hide();
$('#noCity').hide();
$(“#findMyWeather”)。单击(函数(事件){
$(“#成功”).hide();
$(“#失败”).hide();
$('#noCity').hide();
var$cityName=$('#city').val();
if(typeof$cityName==='string'&&&$cityName.length>0){
$.get('/location?city='+$cityName,函数(数据){
}).完成(功能(数据){
$(“#success”).html(data.fadeIn();
$(“#success”).prepend(“

”+$cityName+”

”); $(“#城市”).value=”“//这似乎不起作用 }).fail(函数(){ $(“#失败”).fadeIn(); }); }否则{ $(“#noCity”).fadeIn(); } }); $(“#findLocalWeather”)。单击(函数(事件){ $(“#成功”).hide(); $(“#失败”).hide(); $('#noCity').hide(); $.get('/guessweather',函数(数据){ 如果(数据==“”){ $(“#失败”).fadeIn(); }否则{ $(“#success”).html(data.fadeIn(); } }); }); });
index.html

<!doctype html>
<html>
<head>
 <title>Weather Scraper</title>
 <meta charset="utf-8" />
 <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1" />

 <!--jQuery & Bootstrap-->
 <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

 <!--javascript-->
 <script src="./js/weatherFetcher.js"></script>

 <!--CSS-->
 <link rel="stylesheet" type="text/css" href="./css/weatherStyles.css">

</head>
<body>
    <div class="container">
        <div class="row">
            <div id="heading" class="col-md-6 col-md-offset-3 center">
                <div id="pageIntro">
                    <h1 class="middle">Current Weather</h1>
                    <p class="lead center marginTop">Enter a city to get the current weather or click Local Weather</p>
                </div>
                <div class="form-group">
                    <input type="text" class="form-control marginTop" name="city" id="city" placeholder="Eg. London, Venice, Atlanta, Ho Chi Minh City...">
                </div>
                <button id="findMyWeather" class="btn btn-primary btn-lg marginTop">Get Weather by City</button>
                <button id="findLocalWeather" class="btn btn-primary btn-lg marginTop">Get Your Local Weather</button>
                <div id="alerts">
                    <div id="success" class="alert alert-info marginTop"></div>
                    <div id="failure" class="alert alert-danger marginTop">Could not find weather data for that city. Please try again.</div>
                    <div id="noCity" class="alert alert-danger marginTop">Please enter a city</div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

刮雨机
当前天气

输入城市以获取当前天气或单击当地天气

城市天气预报 了解当地天气 找不到该城市的天气数据。请再试一次。 请输入一个城市
为拒绝的承诺添加错误回调

 app.get('/location', function(req, res) {
        var city = req.query.city;
        weather(city).then(function (currentWeather) {  
            res.json(currentWeather);
        }, function (error) {
            res.json(404,error);
        });
    });
在weather.js中

var request = require('request');
module.exports = function (location) {
  return new Promise(function (resolve, reject) {
    var encodedLocation = encodeURIComponent(location);
    var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + encodedLocation + '&units=imperial&appid=2de143494c0b295cca9337e1e96b00e0';
    if (!location) {
      return reject('No location provided');
    }
    request({url: url, json: true}, function (error, response, body) {
      if (error) {
        return reject('Unable to fetch weather.');
      }
      if(body.main){
        return resolve('The current temperature in ' + body.name + ' is ' + body.main.temp + ' degrees farenheit with humidity at ' + body.main.humidity + '%.');
      }
      return reject(body.message)
    });
  });
};

我添加了这个错误回调,但服务器仍然关闭并在控制台上抛出此消息/Users/marcushurney/Desktop/node-course/Weather-App/public/js/Weather.js:25返回解析(“+body.name+”中的当前温度为“+body.main.temp+”华氏度,湿度为“+body.main.湿度+”);^TypeError:无法读取未定义的属性'temp',是否可以发布console.log(正文)的结果?{coord:{lon:-84.39,lat:33.75},weather:[{id:800,main:'Clear',description:'sky is Clear',icon:'01d}],基站:{temp:24.03,气压:1031,湿度:73,最低温度:19.99,最高温度:28.4},能见度:16093,风速:{speed:3.24,deg:30},云层:{all:1},dt:1451999483,系统:{type:1,id:760,message:0.0086,country:'US',sunrise:1451997779,sunset:1452033799},id:4180439,name:'Atlanta',cod:200}^如果我输入了一个有效的城市名称并得到了一个结果。如果我输入了一个不存在的城市,那么这就是主体:{cod 404,message:'Not found city'}错误如下:/Users/marcushurney/Desktop/node-course/Weather-App/public/js/Weather.js:27返回解析(“+body.name+”中的当前温度为“+body.main.temp+”华氏度,湿度为“+body.main.湿度+”);TypeError:无法读取未定义的属性“temp”