首先,先抛出一个接口 /demo,传一个array;
var express = require('express');
var app = express();
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
var questions=[
{
name:"菜鸟教程",
url:"https://www.runoob.com/react/"
}];
//写个接口123
app.get("/demo",function(req,res){
res.status(200),
res.json(questions)
});
//配置服务端口
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
})
前端逻辑,先接入CDN托管的各个库,然后再说然后
/*react 库 */
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
/* 生产环境中不建议使用 */
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
/*jquery 库 */
<script src="https://cdn.staticfile.org/jquery/2.1.4/jquery.min.js"></script>
/*axios 库 */
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
然后再react的 componentDidMount周期方法中调用接口获取数据,再用 this.setState 方法重新渲染 UI。前端完整代码;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>react demo</title>
</head>
<body>
<div id="example"></div>
</body>
</html>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
<script src="https://cdn.staticfile.org/jquery/2.1.4/jquery.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/babel">
class UserGist extends React.Component {
constructor(props) {
super(props);
this.state = {username: '', lastGistUrl: ''};
}
componentDidMount() {
/* jquery 完成调用 */
/*this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
this.setState({
username: lastGist.name,
lastGistUrl: lastGist.url
});
}.bind(this));*/
/* axios 调用 */
this.serverRequest = axios.get(this.props.source)
.then( (response)=> {
var lastGist = response.data[0];
this.setState({
username: lastGist.name,
lastGistUrl: lastGist.url
});
})
.catch( (error) =>{
console.log(error);
});
}
componentWillUnmount() {
this.serverRequest.abort();
}
render() {
return (
<div>
{this.state.username} 用户最新的 Gist 共享地址:
<a href={this.state.lastGistUrl}>{this.state.lastGistUrl}</a>
</div>
);
}
}
ReactDOM.render(
<UserGist source="http://localhost:3000/123" />,
document.getElementById('example')
);
</script>
如图: