如何在节点js请求消息中访问curl请求的-u?

How is -u of curl request is accessed in node js request message?

我有如下 curl 请求,

curl -u user:password http://localhost:3000/user

如何在服务器上访问http请求中传递的用户和密码?

选项 -u 指定 HTTP Basic Authentication 的用户名和密码。

可通过 Request-Header Authorization (req.headers.authorization) 访问,但使用 base64.

编码

下面的代码将读取 header 并解码字符串,然后将 usernamepassword 存储在单独的变量中。

const b64auth = (req.headers.authorization || '').split(' ')[1] || ''
const strauth = Buffer.from(b64auth, 'base64').toString()
const splitIndex = strauth.indexOf(':')
const login = strauth.substring(0, splitIndex)
const password = strauth.substring(splitIndex + 1)

有关详细信息,请参阅 Basic HTTP authentication with Node and Express 4