NodeJS / Express:从请求中获取用户名和密码

Web*_*rer 6 node.js express

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

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

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

在我的应用程序中:

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

eol*_*eol 9

您将凭据作为基本身份验证标头发送(因为您使用的是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);
   }
});
Run Code Online (Sandbox Code Playgroud)