gpt4 book ai didi

node.js - express.basicAuth 抛出错误

转载 作者:IT老高 更新时间:2023-10-28 23:14:55 27 4
gpt4 key购买 nike

我刚刚使用 express basic auth 在 nodejs 中创建了基本身份验证

var express = require('express');
var app = express();

// Authenticator
app.use(express.basicAuth('testuser','testpassword'));

app.get('/home', function(req, res) {
res.send('Hello World');
});

app.listen(process.env.PORT || 8080);

我收到以下错误。我不知道我哪里出错了。

app.use(express.basicAuth('testuser','testpassword'));
^
TypeError: Object function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};

mixin(app, proto);
mixin(app, EventEmitter.prototype);

app.request = { __proto__: req, app: app };
app.response = { __proto__: res, app: app };
app.init();
return app;
} has no method 'basicAuth'
at Object.<anonymous> (E:\node_modules\npm\login\app.js:5:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3

我对 nodejs 的东西很陌生。任何帮助将不胜感激

最佳答案

正如评论中提到的,Express 4 不再附带中间件,您可以直接从 express repo 复制实现。或使用类似的解决方案:

var express = require('express');
var app = express();

// Authenticator
app.use(function(req, res, next) {
var auth;

// check whether an autorization header was send
if (req.headers.authorization) {
// only accepting basic auth, so:
// * cut the starting "Basic " from the header
// * decode the base64 encoded username:password
// * split the string at the colon
// -> should result in an array
auth = new Buffer(req.headers.authorization.substring(6), 'base64').toString().split(':');
// use Buffer.from in with node v5.10.0+
// auth = Buffer.from(req.headers.authorization.substring(6), 'base64').toString().split(':');
}

// checks if:
// * auth array exists
// * first value matches the expected user
// * second value the expected password
if (!auth || auth[0] !== 'testuser' || auth[1] !== 'testpassword') {
// any of the tests failed
// send an Basic Auth request (HTTP Code: 401 Unauthorized)
res.statusCode = 401;
// MyRealmName can be changed to anything, will be prompted to the user
res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
// this will displayed in the browser when authorization is cancelled
res.end('Unauthorized');
} else {
// continue with processing, user was authenticated
next();
}
});

app.get('/home', function(req, res) {
res.send('Hello World');
});

app.listen(process.env.PORT || 8080);

关于node.js - express.basicAuth 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24283848/

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