以前测试的时候直接是用springboot建立的后端服务器,现在用nodejs 做服务器吧
npm init
生成 package.json文件npm install express
安装 expressnode server1.js
启动服务server1.js代码
const express = require('express')
const app = express()
app.use((request,response,next)=>{
console.log("有人请求了服务器")
next()
})
app.get('/students',(request,response)=>{
const student = [
{id:'001',name:'tom',age:18},
{id:'002',name:'jerry',age:20},
{id:'003',name:'canndy',age:1}
s
]
response.send(student)
})
app.listen(5000, err=>{
if(!err) console.log("服务器开启成功")
})
访问http://localhost:5000/student 获取了学生数据
axios 获取请求代码
import React, {Component} from 'react';
import axios from 'axios'
class App extends Component {
getData = () => {
//axios 返回的数据在response.data 里面
axios.get("<http://localhost:5000/students>").then(({data}) => {
console.log(data);
}).catch(err => {
console.log(err);
})
};
render() {
return (
<div>
<button onClick={this.getData}>点我获取照片</button>
</div>
);
}
}
export default App;