首页 > 解决方案 > 在传递基本身份验证凭据时在 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:""}

它仍然无法正常工作

标签: javascriptnode.jsreactjsapiaxios

解决方案


我必须 在 app.js 文件中包含app.use(basicAuth)以下内容。app.use(cors())


推荐阅读