gpt4 book ai didi

node.js - NodeJS/Express : Get Username and Password from Request

转载 作者:行者123 更新时间:2023-12-04 08:54:01 27 4
gpt4 key购买 nike

我正在使用 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
在我的应用程序中:
app.post('/my_endpoint', async (req, res, next) => {
const kwargs =. req.body;
const userName = req['?'];
const password = req['?'];
});

最佳答案

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

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);
}
});

关于node.js - NodeJS/Express : Get Username and Password from Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63942091/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com