【问题标题】:Can't Connect To API Resource无法连接到 API 资源
【发布时间】:2021-03-26 03:54:27
【问题描述】:

我创建了一个 React 前端,它向我的 api 发出 axios 发布请求。来自前端的代码在用户成功登录后被调用。用户登录成功后,通过 cookie 发送身份验证令牌,该 cookie 用于验证用户是否是管理员并且能够访问api 资源 /api/v1/orders。这在我在本地环境中有效,但是在我将它上传到云端后,我收到了这个错误:

<MY_API>/api/v1/orders:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Adminpage.js:31 Error: Request failed with status code 500
    at e.exports (createError.js:16)
    at e.exports (settle.js:17)
    at XMLHttpRequest.p.onreadystatechange (xhr.js:62)

反应前端

Adminpage.js

const loadOrders = async () => {
    try {
      const res = await axios.get(
        "<MY_API>/api/v1/orders",
        {
          withCredentials: true,
        }
      );
      console.log(res.data.data.orders);
      setOrderData([...res.data.data.orders]);
    } catch (err) {
      console.log(err);
    }
  };

NODEJS 后端

orderRoutes.js

router
  .route('/')
  .get(
    // Only admins can access this route
    authController.requireSignin,
    authController.isAdmin,
    orderController.getAllOrders
  )
  .post(orderController.addOrder);

authController.js

exports.requireSignin = expressJwt({
  secret: process.env.JWT_SECRET,
  algorithms: ['HS256'], // added later
  requestProperty: 'auth', // Decodes the token and assigns to auth object in request object
  getToken: function (req) {
    if (req.cookies.Authorization) {
      return req.cookies.Authorization;
    }
    return null;
  },
});

exports.isAdmin = (req, res, next) => {
  // If users role specified in the req.auth object is not admin, an error is passed to the global error handler otherwise, is able to go to the next function
  if (req.auth.role !== "admin") {
    return next(
      new ApiError(undefined, 403, "User is not authorized for access!")
    );
  }
  next();
};

我的前端 React 代码托管在 AWS 上,我的后端 Nodejs 托管在 Azure 上。

【问题讨论】:

    标签: node.js amazon-web-services azure


    【解决方案1】:

    听起来像是 CORS 问题。您是否在托管 API 的应用服务中启用了 CORS? https://github.com/uglide/azure-content/blob/master/articles/app-service-api/app-service-api-cors-consume-javascript.md

    【讨论】:

    • 您能否提供有关您的 azure 部署的更多详细信息?您是否已将 API 应用程序部署到应用程序服务或虚拟机?您是通过 APIM 访问它还是直接点击应用服务?
    • 我是通过应用服务部署的,直接点击就可以了。
    • 我的建议是首先检查这是否是您的反应应用程序中的身份验证机制的问题,或者这是否是应用程序服务的问题。要检查这一点,请创建并公开一个未经身份验证的 api 端点(一个好的端点是 /api/health),您只需在其中返回 200 成功状态代码。使用这个新端点重新部署您的应用程序,并验证返回 200 还是 500 状态。如果是 200,那么您的身份验证存在问题(检查硬编码值)。但是,如果您仍然为 api/health 端点获得 500,那么它就是您的应用服务。
    猜你喜欢
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 2016-02-29
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多