首页 > 解决方案 > AWS-Lambda 302 收到 Axios 的响应后未重定向(前端)

问题描述

我正在尝试使用无服务器和 AWS-Lambdas 设置 Google-OAuth 流。首先,我有一个按钮,它通过点击 lambda 端点来启动该过程。但是,该页面实际上从未重定向到身份验证页面。相反,我在 FE 上得到一个错误:

Request failed with status code 302

前端逻辑:

const redirectToGoogleOAuth = async (user) => {
  try {
    const endpoint = process.env.GOOGLE_PATH_ENDPOINT;

    const response = await axios.get(endpoint, {
      responseType: 'text',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${user}`,
      },
    });

    // Expect redirect at this point

    return response.data.data;
  } catch (err) {
    throw new Error(err.message);
  }
};

Lambda 端点:

module.exports = async (event, context) => {
  const responseType = 'code'
  const googleAuthorizeURL = 'https://accounts.google.com/o/oauth2/v2/auth'
  const scope = 'openid email https://www.googleapis.com/auth/contacts.readonly'
  const accessType = 'offline'

  try {
    const params = [
      `response_type=${responseType}`,
      `client_id=${googleClientId}`,
      `redirect_uri=${baseURL}`,
      `scope=${scope}`,
      `state="state"`,
      `access_type=${accessType}`
    ]

    const googleOAuthEndPath = `${googleAuthorizeURL}?${params.join('&')}`
    const response = {
      statusCode: 302,
      body: '',
      headers: {
        location: googleOAuthEndPath
      }
    }

    return response
  } catch (err) {
    return response(400, err.message)
  }
}

在 lambda-response 中,我添加了一个带有 google-path 的位置标头。但是,前端似乎没有正确使用响应。前端将 302 解释为错误,而不是重定向到特定页面。关于如何解决这个问题以便它实际重定向的任何想法?

标签: node.jsreactjsamazon-web-servicesaws-lambda

解决方案


Axios 使用XHR,它总是自己跟随重定向,因此 Axios 对此无能为力(除非您依赖黑客,在同一链接中讨论)。

对于这部分,您可能必须使用 Axios 以外的其他东西,例如支持手动重定向的Fetch API

GitHub 用户在上面链接的同一个 Axios 问题中parties提出fetch()等效建议:

fetch("/api/user", {
    redirect: "manual"
}).then((res) => {
    if (res.type === "opaqueredirect") {
        window.location.href = res.url;
    } else {
        return res;
    }
}).catch(handleFetchError);

推荐阅读