gpt4 book ai didi

javascript - 将正文作为 JSON 传递时,Lumen API 返回 422 错误

转载 作者:行者123 更新时间:2023-11-29 23:38:04 24 4
gpt4 key购买 nike

我正在尝试通过 fetch api 从 React 应用程序发布到 php 后端(Lumen 5.3)。

我的帖子如下:

function login(userData, onError, cb) {
return fetch('/v1/auth/login', {
method: 'post',
body: JSON.stringify(userData),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then(checkStatus)
.then(parseJSON)
.then(cb)
.catch(onError);
}

userData 是:

const userData = {
email: this.state.fields.username,
password: this.state.fields.password,
};

但是我收到一个错误:

422 error

哪个表明我的 body 不正确?我怀疑这是因为当我在 postman 中测试一个等效的请求并且不在正文中传递 password 时,我将收到 422 错误:

422 error in postman

这让我相信正文的格式可能不正确?

有点可疑的是,如果我从 php 后端记录我的响应,则没有返回正文。理论上,如果我的 body 格式不正确,我应该从后端收到以下信息:

{
"email": [
"The email field is required."
],
"password": [
"The password field is required."
]
}

最佳答案

原来我的 Lumen API 不接受 JSON 作为主体。

目前的解决方法是按如下方式修改我的请求:

function login(userData, onError, cb) {
return fetch('/v1/auth/login', {
method: 'post',
body: serialize(userData), // no longer passing json
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded' // no longer passing json
},
}).then(checkStatus)
.then(parseJSON)
.then(cb)
.catch(onError);
}

function serialize(obj) {
let str = [];
for(let p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}

userData 是:

const userData = {
email: this.state.fields.username,
password: this.state.fields.password,
};

现在每个人都很高兴 :) 希望这对您有所帮助!

关于javascript - 将正文作为 JSON 传递时,Lumen API 返回 422 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45908517/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com