使用Got库发起OAuth2令牌请求时grant_type参数不被识别问题
问题原因与解决方案
你的问题出在请求数据的编码格式不匹配:
你设置了Content-Type: application/x-www-form-urlencoded,但使用Got的json: payload选项时,Got会将payload序列化为JSON格式发送,而非服务器要求的表单编码格式,导致服务器无法识别grant_type参数。
修复方案1:使用Got的form选项推荐
Got内置了表单编码支持,直接用form替代json即可,它会自动处理表单编码,同时兼容你已设置的Content-Type:
const assert = require("assert"); const got = require("got"); (async() => { var url = "https://example.com/oauth2/v1/token"; var headers = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic xyz' }; var payload = { 'grant_type': 'password', 'scope': 'okta.groups.read okta.users.read', 'username': 'userid', 'password': 'xxxxx' }; var response = await got.post(url, { headers: headers, form: payload, }) console.log(response.statusCode); console.log(response.statusMessage); console.log(response.body); })();
修复方案2:手动编码表单数据
如果需要手动控制编码过程,可以用URLSearchParams将payload转为表单字符串,通过body参数发送:
const assert = require("assert"); const got = require("got"); (async() => { var url = "https://example.com/oauth2/v1/token"; var headers = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic xyz' }; var payload = { 'grant_type': 'password', 'scope': 'okta.groups.read okta.users.read', 'username': 'userid', 'password': 'xxxxx' }; var response = await got.post(url, { headers: headers, body: new URLSearchParams(payload).toString(), }) console.log(response.statusCode); console.log(response.statusMessage); console.log(response.body); })();
注意:需确保已安装并引入got库(执行npm install got安装)。
内容的提问来源于stack exchange,提问作者gvk
相关产品推荐
相关产品推荐

