我想登录,但出现错误:POSThttp://xxx/Token400(错误请求){错误:“ unsupported_grant_type”}
login = () => {
const newItem = {
"Username": this.state.Username,
"Password": this.state.Password,
"grant_type": "password"
}
if (this.state.Username && this.state.Password) {
fetch("http://xxx/Token", {
method: "post",
headers: {
'Accept': 'application/json',
"Content-Type": "application/x-www-form-urlencoded"
},
body: JSON.stringify(newItem)
})
.then(res => res.json())
.then(res => {
console.log(res);
})
}
}
"Content-Type": "application/x-www-form-urlencoded"
和body: JSON.stringify(newItem)
是矛盾的!您不应该(通过Content-Type标头)告诉服务器期望使用表单编码的数据,而是发送JSON数据。服务器很容易对此感到困惑,并尝试应用错误的方法来解析传入的数据。如果您要发送JSON数据,请同时发送正确的Content-Type标头(即application/json
)。
这很可能是您所看到的错误的原因。服务器很可能无法理解您发送给它的数据,因为它试图将其解释为采用表单编码的数据。然后,它进行的第一个验证检查就是检查grant_type值。当它发现(从所见的事物)您根本没有为该参数提交任何值时,它返回一条错误消息,表明它无法处理您的请求,因为它需要您发送有效的grant_type值。
设置
"Content-Type": "application/json"
在标题中应该可以解决此问题。
错误相同
login = () => {
const newItem = {
"Username": this.state.Username,
"Password": this.state.Password,
"grant_type": "password"
}
if (this.state.Username && this.state.Password) {
fetch("http://xxx/Token", {
method: "post",
headers: {
'Accept': 'application/json',
"Content-Type": "application/json"
},
body: JSON.stringify(newItem)
})
.then(res => res.json())
.then(res => {
console.log(res);
})
}
}
没有足够的上下文来回答这个问题,因为错误响应来自未知服务。但是基于它是一个错误的请求响应,其中提到了grant_type,并且您在请求正文中发送了grant_type,因此我认为“密码”不是有效的类型。
我建议您参考所用端点的文档。