Vue项目使用Axios调用AWS Cognito OAuth2接口返回400错误如何解决
问题根因
400错误的核心原因是:axios发送application/x-www-form-urlencoded格式请求时,默认不会自动将JS对象序列化为表单格式字符串,你虽然指定了正确的Content-Type请求头,但请求体实际仍是JSON格式,与AWS Cognito OAuth2接口要求的参数格式不匹配。Postman中调用正常是因为你选择x-www-form-urlencoded格式后,Postman会自动完成参数序列化,不存在格式不匹配问题。
修复方案
方案1:使用URLSearchParams(无额外依赖)
直接将请求参数封装为URLSearchParams实例,axios会自动识别并按表单格式序列化:
auth_api() { const params = new URLSearchParams() params.append('grant_type', 'client_credentials') axios .post( 'https://myawssite.amazoncognito.com/oauth2/token', params, {headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic 123qwe==' }} ) .then(response => (this.token = response.data.access_token)) }
注意:接口返回的token存放在
response.data.access_token字段中,不要直接将整个response对象赋值给token变量。
方案2:使用qs库序列化(适合多参数场景)
如果后续需要传多个参数,可使用qs库完成序列化,先安装依赖:npm install qs
修改代码如下:
import qs from 'qs' auth_api() { axios .post( 'https://myawssite.amazoncognito.com/oauth2/token', qs.stringify({'grant_type':'client_credentials'}), {headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic 123qwe==' }} ) .then(response => (this.token = response.data.access_token)) }
内容的提问来源于stack exchange,提问作者anubiros_theron
相关产品推荐
相关产品推荐

