【问题标题】:NodeJS / Express: Get Username and Password from RequestNodeJS / Express:从请求中获取用户名和密码
【发布时间】:2021-01-04 14:04:32
【问题描述】:

我正在使用 NodeJS 和 Express,我想从请求中获取用户名和密码参数。我已经搜索了一段时间,但我找不到我的答案。

我想接受来自 cURL 命令的 user 参数:

curl --request --POST -u USERNAME:PASSWORD -H "Content-Type:application/json" -d "{\"key":\"value\"}" --url https://api.example.com/my_endpoint

在我的应用程序中:

app.post('/my_endpoint', async (req, res, next) => {
    const kwargs =. req.body;
    const userName = req['?'];
    const password = req['?'];
});

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    您将凭据作为基本身份验证标头发送(因为您使用 curl 的 -u 选项)。因此,为了从您的请求中获取凭据,您需要访问此标头并对其进行解码。这是执行此操作的一种方法:

    app.post('/my_endpoint', async (req, res, next) => {
       if(req.headers.authorization) {
         const base64Credentials = req.headers.authorization.split(' ')[1];
         const credentials = Buffer.from(base64Credentials, 'base64').toString('utf8');
         const [username, password] = credentials.split(':');
         console.log(username, password);
       }
    });
    

    【讨论】:

    • 找了这么久的简单答案,谢谢!
    【解决方案2】:

    How do I consume the JSON POST data in an Express application

    我会这样做

    假设您的通话包含这样的 json 内容:

    删除-u USERNAME:PASSWORD

    编辑 -d "{ "username": "user", "password": "test" }"

    curl --request --POST -H "Content-Type:application/json" -d "{ "username": "user", "password": "test" }" --url https://api.example.com/my_endpoint
    

    然后您可以使用以下命令访问这些变量:

    const userName = req.body.username;
    const password = req.body.password;
    

    请注意,您需要在 express 中使用 bodyParser 中间件才能访问正文变量。

    【讨论】:

    • 我绝对没有在请求正文中传递用户名和密码。这不安全。
    • 取决于加密但是是的,这不是最好的方法!对不起
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 2019-08-14
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多