嗨,我正在尝试将两个api请求合并到我的简单node.js网站上。我将它们都分开工作,但是我很难将两者结合在一起以在同一页面上工作。
request(url2, function (err, response, body) {
if(err){
res.render('index', {news: null, error: 'Error, please try again',initials111:initials,test:potatoes});
} else {
let news = JSON.parse(body);
if(news== undefined){
res.render('index', {news: null, error: 'Error, please try again',initials111:initials,test:potatoes});
}
else{
let newsText = `${news.articles[0].title}` ;
res.render('index', {news: newsText, error: null,initials111:initials,test:potatoes});
}
}
}
);
request(url, function (err, response, body) {
if(err){
res.render('index', {weather: null, error: 'Error, please try again',initials111:initials,test:potatoes});
} else {
let weather = JSON.parse(body);
if(weather.main == undefined){
res.render('index', {weather: null, error: 'Error, please try again',initials111:initials,test:potatoes});
} else {
if (rain == "0,rain"){
let weatherText = `It's ${weather.main.temp} degrees celsius and with wind speeds of ${weather.wind.speed} mph in ${weather.name} ${weather.sys.country}! & ${weather.weather[0].description}` ;
res.render('index', {weather: weatherText, error: null,initials111:initials,test:potatoes});
}
else{
let weatherText = `It's ${weather.main.temp} degrees celsius and with wind speeds of ${weather.wind.speed} mph in ${weather.name} ${weather.sys.country}!` ;
res.render('index', {weather: weatherText, error: null,initials111:initials,test:potatoes});
}
}
}
});
这是每个请求的代码的两个部分。如果需要,我可以附上网站的屏幕截图。如果我将它们都放在server.js文件中,则会收到很多错误。任何人都可以帮助/提供提示吗?
例如,当我将它们都粘贴到server.js并尝试访问网站时,我会收到此错误
ReferenceError: C:\NodeShit\weather-rough\views\index.ejs:42
40|
41|
>> 42| <% if(news !== null){ %>
43| <p><%= news %></p>
44| <% } %>
45|
news is not defined
at eval (eval at compile (C:\NodeShit\weather-rough\node_modules\ejs\lib\ejs.js:618:12), <anonymous>:11:8)
at returnedFn (C:\NodeShit\weather-rough\node_modules\ejs\lib\ejs.js:653:17)
at tryHandleCache (C:\NodeShit\weather-rough\node_modules\ejs\lib\ejs.js:251:36)
at View.exports.renderFile [as engine] (C:\NodeShit\weather-rough\node_modules\ejs\lib\ejs.js:482:10)
at View.render (C:\NodeShit\weather-rough\node_modules\express\lib\view.js:135:8)
at tryRender (C:\NodeShit\weather-rough\node_modules\express\lib\application.js:640:10)
at Function.render (C:\NodeShit\weather-rough\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (C:\NodeShit\weather-rough\node_modules\express\lib\response.js:1008:7)
at Request._callback (C:\NodeShit\weather-rough\server.js:63:13)
at Request.self.callback (C:\NodeShit\weather-rough\node_modules\request\request.js:185:22)