1 回答
TA贡献1851条经验 获得超5个赞
为了配合npm,我个人项目是用的ES6的Fetch来进行HTTP请求
import React from 'react';
class Test extends React.Component{
constructor(...props){
super(...props);
this.state = {
username:'',
password:''
};
}
http(url, options, type = 'json') {
options = options || {};
options.credentials = 'include';
return fetch(url, options).then((resp)=> {
if (resp.ok) {
return resp[type]();
} else {
return resp[type]().then((err)=> {
throw new AppError(err.errmsg, err.errcode);
});
}
});
}
onSubmit(e){
e.preventDefault();
this.http('/api/user/login', {
method: 'POST',
body: JSON.stringify(this.state),
headers: {
'Content-Type': 'application/json'
}
}).then((data)=> {
console.log(data);
}).catch((e)=>alert(e.message)});
}
render(){
return (
<form onSubmit={e=>this.onSubmit(e)}>
<input type="text" value={this.state.username} placeholder="用户名" onChange={e=>this.setState({username:e.target.value})}/>
<input type="password" value={this.state.password} placeholder="密码" onChange={e=>this.setState({password.target.value})}/>
<button>提交</button>
</form>
)
}
添加回答
举报