【问题标题】:AWS-Lambda 302 Not Redirecting after getting response from Axios (Frontend)AWS-Lambda 302 收到 Axios 的响应后未重定向(前端)
【发布时间】:2020-06-23 11:15:15
【问题描述】:

我正在尝试使用无服务器和 AWS-Lambda 设置 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.js reactjs amazon-web-services aws-lambda


    【解决方案1】:

    Axios 使用 XHRalways follows redirects by itself and therefore Axios can't do anything about it(除非您依赖 hack,在同一链接中讨论)。

    这部分你可能不得不使用 Axios 以外的东西,比如Fetch APIsupports manual redirects

    GitHub 用户 parties 在上面链接的同一个 Axios 问题中建议 the fetch() equivalent

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

    【讨论】:

      猜你喜欢
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 2018-03-12
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多