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



我正在使用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['?'];
});

您将凭据作为基本的auth头发送(因为您使用的是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);
}
});

如何在Express应用程序中使用JSON POST数据

我会这样做

假设您的调用包含如下json内容:

删除-u用户名:密码

编辑-d";{"用户名":"用户","密码":"测试"}

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中间件,以便能够访问主体变量。

最新更新