node.js - Node-Express:过滤请求查询并显示剩余数据
问题描述
我是节点查询的新手。我正在为我的后端应用程序使用 Node express。我有一个嵌套的 json,它具有三种语言选项,内部语言有auth
、dashboard
、data
和data1
选项。我想过滤查询并在浏览器中显示其余的 json 数据。例如,如果我像这样输入 url:http://localhost:5000/?namespaces=auth&languages=en,fi
那么它将显示语言en
和fi's
数据,并且namespaces
我想显示auth's
数据。为了显示数据,我创建了一个输出空对象并希望将其添加到我的输出对象中。但不知道该怎么做。
我在codesandbox中分享了我的代码。
这是我的 json 数据
{
"en": {
"auth": {
"welcomeMessage3": "Hi John"
},
"dashboard": {
"welcomeMessage": "Hi Doe"
},
"data (1)": {
"welcomeMessage3": "Hi Jonny"
},
"data": {
"welcomeMessage3": "Hi Monty"
}
},
"fi": {
"auth": {
"welcomeMessage3": "Moi name "
},
"dashboard": {
"welcomeMessage": "Moi dashboard"
},
"data (1)": {
"welcomeMessage3": "Moi data 1"
},
"data": {
"welcomeMessage3": "Moi data"
}
},
"sv": {
"auth": {
"welcomeMessage3": "Hej John"
},
"dashboard": {
"welcomeMessage": "Hej dashboard"
},
"data (1)": {
"welcomeMessage3": "Hej data"
},
"data": {
"welcomeMessage3": "Hej data"
}
}
}
这是我的快递应用
const express = require('express')
const app = express()
const port = 5000
const translationData = require('./translations'); // My json
const filterTranslations = (namespaces, languages) => {
let output = {};
const translations = { ...translationData };
console.log("I am typing Languages", languages);
console.log("I am typing namespace", namespaces);
for (const lng in translations) {
console.log("languages are coming from translation json", lng);
if (lng.length !== 0 && lng !== languages) {
delete translations[lng];
console.log("Delete rest of the language", lng);
} else {
for (const ns in translations[lng]) {
if (ns.length !== 0 && ns !== namespaces) {
delete translations[lng][ns];
console.log("delete rest of the Namespace", ns);
}
}
}
}
return output;
};
app.get('/', (req, res) => {
res.send(
filterTranslations(
req.query.namespaces,
req.query.languages,
)
)
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
解决方案
有几个错误:
- 该函数
filterTranslations
应该返回一个值,在这里translations
, - 您
if
声明中的条件不正确 :lng !== languages
,在您的示例中,languages = 'en,fi'
将lng
是en
orfi
。看String.includes( searchString [, position ])
或split
你的languages
使用Array.includes( searchElement[, fromIndex])
。
希望对你有帮助,祝你有个美好的一天!
推荐阅读
- css - CSS如何将不同尺寸的图像与行内的文本对齐?
- python - Tensorflow对象检测,在教程中重新排列代码时列表索引超出范围错误
- git - 如何确保在推送到 repo 之前应用 Mac 上重命名目录的区分大小写?
- pandas - Pandas udf 循环遍历 PySpark 数据帧行
- visual-studio-code - 如何获取要显示的类型提示?
- swift - becomeFirstResponder 在 viewWillAppear 中不起作用
- mysql - 将十进制转换为字符串并选择所有以 .99 结尾
- c# - 在 OData4 中定义自定义字符串函数
- r - 在 R 中正确更新初始化 var 和函数排序的递归解决方案
- flutter - 如何使 SliverAppBar 的标题垂直居中?