我正在使用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['?'];
});
答案 0 :(得分:2)
您将凭据作为基本身份验证标头发送(因为您正在使用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);
}
});
答案 1 :(得分:0)
How do I consume the JSON POST data in an Express application
我会这样做
假设您的通话包含这样的json内容:
删除 -u USERNAME:PASSWORD
编辑 -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中间件才能访问主体变量。