我在express中设置了一条路线,我想根据给定的字符返回一个随机字符串。
const express = require('express');
const router = express.Router();
function randomChar(charArray) {
//returns random character based of character array
return charArray[Math.floor(Math.random() * (charArray.length))];
}
function exerciseGenerator(charArray) {
//returns randomized string
let string = '';
let i;
for (i = 0; string.length < 100; i += 1) {
string += randomChar(charArray);
// insert space at random
if (string.slice(-2) !== ' ' && Math.random() < 0.3 && string.length < 100) {
string += ' ';
}
}
return string;
}
const exercises = {
items: [
{
id: 0,
name: 'title 0',
string: ['d','f'],
},
{
id: 1,
name: 'title 1',
string: ['f', 'j'],
},
],
};
// specific routing with parameters
router.get('/:id', (req, res) => {
let exercise = exercises.items[req.params.id];
if (exercise.string.constructor === Array) {
exercise.string = exerciseGenerator(exercise.string);
}
res.json({ api: exercise });
});
module.exports = router;
因此,向localhost:3000 / api / practice / 0发出请求会返回此示例:
“df d f dfdf f d d f d d d d ddff f”
现在这是它应该如何工作,但有一点需要注意:响应在后续调用中给出相同的随机字符串。只有当我重新启动服务器时,我才会得到一个新的随机字符串。显然,我认为它的工作原理并不是它真正起作用的方式。
为什么会发生这种情况?如何解决这个问题?
答案 0 :(得分:2)
问题是您在第一个请求上覆盖exercises.items[0].string
并将类型从数组更改为字符串,因为每个下一个请求都会返回相同的结果。
您应该删除条件:if (exercise.string.constructor === Array)
以使其正常工作:
router.get('/:id', (req, res) => {
let exercise = exercises.items[req.params.id];
let string = exerciseGenerator(exercise.string);
res.json({ api: string});
});
答案 1 :(得分:1)
我的最终解决方案是添加更新功能并更新运动变量,如下所示:
select
department_id,
department_name,
(select count(*) from student s where s.department_id = d.department_id) as student_count
from department d
order by 3 desc;