看来用Express v3实现基本HTTP身份验证很简单:

app.use(express.basicAuth('username', 'password'));

不过,版本4(我使用的是4.2)删除了basicAuth中间件,所以我有点卡住了.我有以下代码,但它不会导致浏览器提示用户输入凭据,这正是我想要的(我认为旧方法会这样做):

app.use(function(req, res, next) {
    var user = auth(req);

    if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
        res.writeHead(401, 'Access invalid for user', {'Content-Type' : 'text/plain'});
        res.end('Invalid credentials');
    } else {
        next();
    }
});

推荐答案

我用原来basicAuth的代码找到了答案:

app.use(function(req, res, next) {
    var user = auth(req);

    if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
        res.statusCode = 401;
        res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
        res.end('Unauthorized');
    } else {
        next();
    }
});

Node.js相关问答推荐

如何在Node js中从MongoDB获取特定数据,使用GET方法?

MongoDB-如何验证Document字段以仅允许特定的文件扩展名?

使用NodeJS输出检索Base64图像的网络报废

设置默认 node 版本

React原生Nodejs兼容性问题

为什么 docker 容器内的应用程序无法访问它自己的 API 端点?

如何使用包含条件正确分页的 sequelize 查询?

对 google api v3 的 Axios 请求返回加密(?)数据

MongoDB 根据使用聚合的条件从嵌套数组中删除对象

如何使动态私有IP地址静态?

Node JS:自动 Select `http.get`与`https.get`

如何在 Node.js 的 console.log() 中创建换行符

Node.js 服务器中没有缓存

React Native ios build:找不到 node

如何让should.be.false语法通过 jslint?

webpack css-loader 在外部样式表的 url() 引用中找不到图像

node.js 中存储的模块变量在什么范围内?

在 react-router v4 中使用 React IndexRoute

Heroku + Node:找不到模块错误

找不到在 docker compose 环境中运行的 node js 应用程序的模块