![](/img/trans.png)
[英]How to send axios post request with date object in request body?
[英]How can pass body dynamically when send request - axios?
我有 4 个单独的输入发送更新用户数据的请求,所以我创建了一个函数,该函数接受一个参数并将其传递给 body 但它不起作用我收到 500 状态错误!
但是当我声明主体名称时,它适用于一个输入。
const sendReq = (bodyName) => {
let AuthStr =
'Bearer ...';
const headers = {
'Content-Type': 'application/json',
Authorization: AuthStr,
};
Api.post(
'/edit/user',
{
email: bodyName, // here it's work "but i want this be more dynimacly."
// bodyName: bodyName, // error 500
},
{
headers,
},
).then((res) => {
console.log(res.data);
});
};
// for update email
const updateEmail = (newEmail) => {
if (validateEmail(newEmail)) {
setError('');
sendReq(email);
console.log('yay!');
} else {
setError('error....');
}
};
// password
const updatePassword = () => {
....
sendReq(password);
}
// and so on...
我解决了它:) 我添加了 2 个参数,第一个是属性名称,第二个参数是属性值,如下所示:
const sendReq = (bodyName, bodyVal) => {
let AuthStr =
'Bearer ..';
const headers = {
'Content-Type': 'application/json',
Authorization: AuthStr,
};
let body = {};
body[bodyName] = bodyVal;
console.log(body);
Api.post('/edit/user', body, {
headers,
})
.then((res) => {
console.log(res.data); // works :"D
})
.catch((err) => console.log(err));
};
这是我打电话的时候。
sendReq('email', email);
sendReq('password', password);
这是一个后端问题,API 需要请求正文中的“email”变量,而不是 bodyName。 这就是它抛出错误的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.