REST API和Express新手不了解重复结果

时间:2016-03-10 14:25:52

标签: api rest express

当我第一次获得正确的输出时运行我的代码,但是如果我刷新该页面并再次运行代码,则输出包含第一个输出和新输出。要获得一个新的形式,我必须重新启动服务器并刷新页面,任何人都可以解释为什么会发生这种情况以及我如何解决它。

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
var PORT = 3000;

var x = {
"word" : null,
"maxValue" : null
}

var maxValueArray = [];
var output = {
        "status": "ok",
        "results": []
    }

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public/'));

//GET
app.get('/', function (req,res) {
    res.send();
}); 

app.post('/', function(req, res) {

var word = req.body.word;
var maxValue = req.body.maxValue;

if (word != "fizz" && word != "buzz" && word != "fizzbuzz") {
        output.status = "error";
    return res.status(400).send(output);
}

if (maxValue < 1) {
    output.status = "error";
    return res.status(400).send(error); 
}

var html;
for (i=1; i <= maxValue; i++) {
    maxValueArray.push(i);
    }                   

    if (word === "fizz" && maxValue > 0) {
    maxValueArray.forEach(function (index){
        if (index%3 === 0) {
            output.results.push(index); 
            return html = output;                                       
        }       
    });

    res.send(html);
    } else if (word === "buzz" && maxValue > 0) {

        maxValueArray.forEach(function (index){
            if (index%5 === 0) {
                output.results.push(index); 
                html = output;                                      
            }
        }); return res.send(html);

    } else if (word === 'fizzbuzz' && maxValue > 0) {
        maxValueArray.forEach(function (index){
            if (index%3 === 0 && index%5 === 0) {
                output.results.push(index); 
                html = output;                          
            }
        }); return res.send(html);  
} 
});
app.listen(PORT, function () {
console.log('Express listening on port ' + PORT);
});

1 个答案:

答案 0 :(得分:0)

您应该在回调函数中声明变量maxValueArray并输出。

const crypto = require('crypto');
crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, key) => {
  if (err) throw err;
  console.log(key.toString('hex'));  // 'c5e478d...1469e50'
});