HTML页面
import React, {Component} from 'react';
class Communication extends Component {
constructor(props) {
super(props);
this.getRequest = this.getRequest.bind(this);
this.postRequest = this.postRequest.bind(this);
}
getRequest(){
fetch('/api/get?name=nihao&age=30',{method:'get'}).then(res=>res.json()).then(data=>{
console.log(data);
}).catch(error=>console.log(error));
}
postRequest(){
let obj={name:'朱一龙',age:31};
fetch('/api/post',{method:'post', body:JSON.stringify(obj),headers:{'content-type':'application/json'}}).then(res=>res.json()).then(data=>{
console.log(data);
}).catch(error=>{console.log(error)});
}
render() {
return <div>
<button onClick={this.getRequest}>get请求</button>
<button onClick={this.postRequest}>post请求</button>
</div>
}
}
export default Communication;
服务器页面
let express = require("express");
let bp = require('body-parser');
let app = express();
// app.use(bp.urlencoded({extended:false}));
app.use(bp.json());
app.get('/api/get',function (req,res) {
console.log(req.query.name,req.query.age);
res.json({msg:'这是get请求的返回数据'});
});
app.post('/api/post',function (req,res) {
console.log(req.body.name,req.body.age);
res.json({msg:'这是post请求的返回数据'});
});
app.listen(4466);