【发布时间】:2020-02-16 15:22:32
【问题描述】:
在我的 api 测试中,它能够如下图所示运行。但是,当我尝试在 React.JS 中编码时,无法传入用户 ID。这是什么问题?
但是当我尝试在前端编码时,无法将用户 ID 传递给 api。 考虑下面的代码:
constructor (props){
super(props);
const Users_id = localStorage.getItem('id');
this.state ={
users_id: Users_id,
event_name: '',
event_email: '',
event_description: '',
event_type: '',
event_location: '',
start_date: '',
end_date: '',
history: PropTypes.object.isRequired
}
this.create = this.create.bind(this);
this.onChange = this.onChange.bind(this);
}
create(){
// const loginEmail = localStorage.getItem('loginEmail');
const Users_id = localStorage.getItem('id');
this.setState({Users_id})
// console.log(loginEmail)
PostData('api/event/submit', this.state).then ((result) => {
let responseJSON = result;
console.log(responseJSON);
console.log(this.state)
});
}
console.log(responseJSON) 中显示的错误:
//更新后的数据
return new Promise((resolve, reject) => {
fetch( BaseUrl+type, {
method: "POST",
body: JSON.stringify(userData),
Accept: 'application/json',
// mode: 'no-cors',
headers:
{
'Content-Type': 'application/json'
},
})
.then((response) => response.json())
.then((responseJson) => {
resolve(responseJson);
})
.catch((error)=>{
console.error('Error:', error);
})
});
【问题讨论】:
-
您的 API 是否期望 users_id 为数字?还是字符串化的数字?
-
@Jacob ya,users_id 是数字。
-
我相信 getItem 返回一个字符串。尝试在更新状态之前输入
console.log(typeof Users_id)。 -
你能展示你的 PostData 方法的代码吗?
-
@Jacob 没错,控制台日志的响应是字符串。那么有没有办法将字符串转换为数字呢?