javascript - 在传递基本身份验证凭据时在 axios 上获取身份验证错误
问题描述
我已经用 nodejs 处理了我的服务器端的基本身份验证,请参考下面的代码。
module.exports = basicAuth;
// require("dotenv").config({ path: "./.env" });
require("dotenv/config");
// async function basicAuth(req, res, next) {
function basicAuth(req, res, next) {
// check for basic auth header
if (
!req.headers.authorization ||
req.headers.authorization.indexOf("Basic ") === -1
) {
return res.status(401).json({ message: "Missing Authorization Header" });
}
console.log(req.headers.authorization);
// verify auth credentials
const base64Credentials = req.headers.authorization.split(" ")[1];
// console.log(base64Credentials);
const credentials = Buffer.from(base64Credentials, "base64").toString(
"ascii"
);
const [username, password] = credentials.split(":");
// const user = await userService.authenticate({ username, password });
let user = 0;
if (
username == process.env.API_USERNAME &&
password == process.env.API_PASSWORD
) {
user = 1;
}
if (!user) {
return res
.status(401)
.json({ message: "Invalid Authentication Credentials" });
}
next();
}
我已经app.use(cors())
在我的 app.js 中添加了,我可以使用基本身份验证访问所有路由。我已经使用 react 编写了我的前端应用程序,并且我正在使用 axios 使用我创建的路由来获取数据。当我尝试在不使用基本身份验证的情况下访问它时,请注意相同的 API 的工作。下面是使用 axios 访问数据的代码。
try {
require("dotenv").config();
console.log(this.state.params);
let urlparam = "http://localhost:5000/users/" + this.state.params;
let result;
result = await axios({
url: "http://localhost:5000/users",
method: "get",
withCredentials: true,
headers: {
authorization: "Basic c2Fsb29uOnNhbG9vbg==",
},
});
} catch (err) {
console.log(err);
}
使用上面的代码我得到: 请求的资源需要用户身份验证。 在 Edge 浏览器和 Google chrome 上,我收到错误消息: CORS 策略已阻止从源“ http://localhost:3000 ”访问“ http://localhost:5000/users ”处的 XMLHttpRequest:对预检请求的响应不'不通过访问控制检查:请求的资源上不存在'Access-Control-Allow-Origin'标头。 和 xhr.js:178 GET http://localhost:5000/users net::ERR_FAILED
请记住,我已经为所有路由添加并使用了 cors 中间件,并且它以前可以正常工作。我什至尝试单独传递身份验证参数,例如
auth:{username:"",password:""}
它仍然无法正常工作
解决方案
我必须
在 app.js 文件中包含app.use(basicAuth)
以下内容。app.use(cors())
推荐阅读
- gradle - Gitlab CI 上下文中的 Gradle-release 插件和 SSH 配置
- firebase - Firebase addListenerForSingleValueEvent 调试模式与正常模式的工作方式不同
- excel - 循环以下浏览器文档完成
- visual-c++ - 用clang-cl构建clang的过程中缺少什么“version.lib”?
- mobile - 在 stripe.NET-payments 基本示例(Xamarin)中找不到类型
- asp.net-core - ABCpdf - 使用 .NET Core 2.1 下载 PDF - HttpContext/HttpResponse
- spring - 使用非 JPA Repository 对象的 SpringBoot 应用程序的 junit 测试用例
- swift - 有没有办法在 MacOS 中创建圆形 NSLabel?
- java - VerticalGroup 内的标签不保持在左侧
- dart - 无法在颤动的两个页面之间传递空变量