node.js - 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 解释为错误,而不是重定向到特定页面。关于如何解决这个问题以便它实际重定向的任何想法?
解决方案
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);
推荐阅读
- scala - Scala Seq[Seq[SomeClass]] 可变集合的类型不匹配
- linux - 尝试: gem pristine bootsnap --version 1.3.1 忽略 bootsnap-1.3.1,因为它的扩展没有构建。试试: gem pristine bootsnap --version 1.3.1
- python - Python Regex-保持字母字符连续相邻/在数字序列内
- r - 博客和数据文件
- regex - 正则表达式使用条件检查用户 ID 是否有效
- java - 一个简单的属性练习#java
- image-processing - 相关性(偏移检测)问题 - 信号功率集中在域边缘
- unit-testing - 在 Kotlin 中,`when` 是什么意思?
- inner-join - Power Query 联接和比预期更多的列
- javascript - 从动态 Web 组件(React/Vue/Angular)创建 .eml 文件 [已编译的 html 字符串]