首页 > 解决方案 > Node-Express:过滤请求查询并显示剩余数据

问题描述

我是节点查询的新手。我正在为我的后端应用程序使用 Node express。我有一个嵌套的 json,它具有三种语言选项,内部语言有authdashboarddatadata1选项。我想过滤查询并在浏览器中显示其余的 json 数据。例如,如果我像这样输入 url:http://localhost:5000/?namespaces=auth&languages=en,fi那么它将显示语言enfi'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}`)
    })

标签: node.jsjsonexpress

解决方案


有几个错误:

  • 该函数filterTranslations应该返回一个值,在这里translations
  • if声明中的条件不正确 : lng !== languages,在您的示例中,languages = 'en,fi'lngenor fi。看String.includes( searchString [, position ])split你的languages使用Array.includes( searchElement[, fromIndex])

希望对你有帮助,祝你有个美好的一天!


推荐阅读