每次我重新启动服务器时,第一个 post 请求中的数据都会保存在 var prodctNum 中,但整个 var request = http.get 函数会变成 NAN,直到我再次发布为止。
我需要做什么?
//Global Vars
app.use(function(req, res, next) {
res.locals.priceES = null
res.locals.lowPrice = null
res.locals.priceArray = null
next()
})
//Set Static Path
app.use(express.static(path.join(__dirname, '/public')))
app.get('/', function(req, res) {
res.render('newpage') //change to index
})
var currencyGBP = ""
function getCurrency() {}
getCurrency()
var priceES = ""
var priceArray
app.post('/', function(req, res) {
var proudctNum = req.body.product
console.log("Product num is:.. " + proudctNum);
priceArray = [{
"ID": 0,
"price": Math.round(priceES / currencyEUR),
"country": "ES"
}, {
"ID": 6,
"price": 10,
"country": "TEST"
}]
var url = "API" + proudctNum + "&store=";
//server rquest
var request = http.get(url + "RU", function(res) {
var body = ""
res.on("data", function(chunk) {
body += chunk;
})
res.on("end", function() {
var profile = JSON.parse(body);
priceRU = profile[0].productPrice.current.value;
//console.log("Russia Price is:.." + priceRU);
})
});
var lowPrice = priceArray.reduce(function(prev, curr) {
return prev.price < curr.price ? prev : curr;
});
//console.log(priceArray[0].price);
console.log(lowPrice)
function FINALRENDER() {
console.log(priceArray)
res.render('newpage', priceArray)
}
setTimeout(FINALRENDER, 5000)
})
html/ejs代码
<form method="POST" action="/">
<input type="text" name="product" onfocus="this.value=''" value="TEXT" class="formInput">
<p class="text-faded mb-5"><BR>TEXTEXT </p>
<input type="submit" class="btn btn-primary btn-xl js-scroll-trigger" href="/" value="TEXT"></a>
最佳答案
你检查一下你的 NodeJS 和 JavaScript 方法是否都是 POST 吗?当我曾经写过 GET 并在另一边写 POST 时,我多次遇到过这个问题;)
关于javascript - POST 请求仅在服务器启动后第二次有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48288752/