我试着寻找这个答案但却找不到任何东西。
在我的node.js索引路由中,我正在创建一个捕获数据并将其发送到视图的http请求。我注意到,当我在浏览器中访问该页面时,视图不会使用最新数据进行更新,只有在我重新保存index.js文件时它才会更新。
index.js
var express = require('express');
var router = express.Router();
var request = require('request');
var url_fx = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22EURUSD%2CUSDJPY%2CUSDCAD%2CUSDCHF%2CGBPUSD%2CAUDUSD%2CNZDUSD%2CUSDMXN%2CEURGBP%2C%20EURJPY%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
var fx_feed;
//console.log(url_fx)
request(url_fx, function(err, resp, body) {
body = JSON.parse(body);
fx_feed="";
if (!body.query.results) {
fx_feed = "No results found. Try again.";
} else {
fx_feed = body.query.results.rate;
console.log(fx_feed)
console.log("updated")
}
})
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Title', fx:fx_feed });
});
module.exports = router;
为什么我在浏览器中点击页面时没有更新?即使我清除缓存,它也不会更新。
控制台(浏览器请求后)
GET / 304 1256.650 ms - -
GET /stylesheets/style.css 304 7.983 ms - -
GET / 304 87.536 ms - -
GET /stylesheets/style.css 304 3.365 ms - -
控制台(在文本编辑器中保存文件后)
{ id: 'EURJPY',
Name: 'EUR/JPY',
Rate: '138.5375',
Date: '8/21/2015',
Time: '3:57pm',
Ask: '138.5450',
Bid: '138.5300' } ]
updated
答案 0 :(得分:1)
您需要将请求放入路线:
var express = require('express');
var router = express.Router();
var request = require('request');
var url_fx = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22EURUSD%2CUSDJPY%2CUSDCAD%2CUSDCHF%2CGBPUSD%2CAUDUSD%2CNZDUSD%2CUSDMXN%2CEURGBP%2C%20EURJPY%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
var fx_feed;
/* GET home page. */
router.get('/', function (req, res, next) {
request(url_fx, function (err, resp, body) {
body = JSON.parse(body);
fx_feed = "";
if (!body.query.results) {
fx_feed = "No results found. Try again.";
} else {
fx_feed = body.query.results.rate;
console.log(fx_feed)
console.log("updated")
}
res.render('index', {
title: 'Title',
fx: fx_feed
});
})
});
module.exports = router;