首页 > 解决方案 > 处理同一路径中的多个参数

问题描述

我正在使用 node 和 express 构建一个 API,它可以使用通用密码加密和解密消息。在我的 API 中,标准路径“格式”是 /<encrypt/decrypt>/<key(s)>。我目前不确定处理多个“密钥值”的最佳方式,因为某些密码可能需要多个密钥值进行加密。

const express = require("express");
const app = express();
const port = 3000;

const checkInput = require("./input_validator");

//import affine cipher utilities
const [affine, reverseAffine, affineKeyValidator] = require("./ciphers/affine");

app.get("/affine/encrypt/:string/:key", (req, res) => {
  if (checkInput(req.params.string)) {
    let key = JSON.parse("[" + req.params.key + "]");
    if (affineKeyValidator(key[0])) {
      res.send({ text: affine(req.params.string, key[0], key[1]) });
    }
  }
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

以上是我目前的实现。一个示例路径是 /affine/encrypt/hiddenmessage/1,25,它在技术上运行良好,但我觉得这似乎不是实现我正在寻找的最佳方式。有没有更有效的方法来构建它?

标签: node.jsapiexpress

解决方案


此格式的值可以以QueryParams. 您使用的是普通 express.js,因此,当您从前端/客户端发送数据时,您可以将该数据附加到 HTTP 查询参数中,然后可以通过以下方式检索这些数据:

const query = req.query;// query = {key:"abc", value: "123"}

推荐阅读