[英]Express server on Node shuts down when data can't be fetched from get request
當用戶輸入城市名稱時,此應用會獲取當前天氣,也可以使用您的IP地址獲取您的當前位置和當前天氣。
問題:當用戶鍵入一個不存在的城市時,如“ jklsafbhjbdsfjhbf”,失敗消息如預期般消失,但是服務器關閉,並且如果不重新啟動服務器,該用戶將無法再發出天氣請求終點站。
我認為問題出在文件weather.js的承諾范圍之內,或者可能是我在weatherFetcher.js的前端或app.js的后端處理get請求的方式
需要幫助解決此問題,以便服務器不會關閉,並且用戶可以繼續發出天氣請求。
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);
});
});
});
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.');
} else {
return resolve('The current temperature in ' + body.name + ' is ' + body.main.temp + ' degrees farenheit with humidity at ' + body.main.humidity + '%.');
}
});
});
};
location.js
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);
}
});
});
}
weatherFetcher.js
$(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();
}
});
});
});
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)
});
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.