Data request
live-server
what islive-server
live-server
It is a small server with real-time loading function, which can be used to crack html/css/javascript
, but cannot be used to deploy the final site. In other words, we can use it live-server
as a real-time server in the project to view the effect of the developed webpage or project in real time.
So this is our mock
service
installation
npm
Installation method (recommended)
npm i -g live-server
Modify package.json
, addmock
"scripts": {
"mock": "live-server ./src/mock --port=9000"
},
Of course, in src/mock
case you have to have a json
file, then only need to enter in a terminal npm run mock
, your service can be started.
vscode
Install using plugin
Find it in the plugin repository live server
and install it
Click on the lower right corner Go Live
to start the service. The default port is 5500.
axios
Axios
It is based on promise
a HTTP
library that can be used in the browser and node.js
in.
- Support browser and
node.js
- stand by
promise
- Ability to intercept requests and responses
- Able to convert request and response data
- Can cancel request
- Automatically convert
JSON
data - Browser support prevention
CSRF
(cross-site request forgery)
npm install --save axios
Quote after installationaxios
import axios from "axios"
We componentDidMount
call in this hook function axios
to request data, the complete code is as follows
import React, {
Component } from "react";
import axios from "axios"
export default class Api extends Component {
constructor(props){
super(props)
this.state = {
param: ""
}
}
// 钩子函数,当这个Component 渲染完成后自动调用
componentDidMount(){
axios.get("http://127.0.0.1:9000/data.json")
.then((data)=>{
console.log(data.data.log_pb.impr_id)
this.setState({
param: data.data.log_pb.impr_id
})
})
}
render(){
return ( <div>
Api 组件
<div> {
this.state.param}</div>
</div> )
}
}
Cross-domain issues
Front-end proxy
/node_modules/react-scripts/config/webpackDevServer.config.js
modify
proxy:{
"/api":{
// target : "http://www.weather.com.cn/data/cityinfo/"
target: "地址",
// changeOrigin
changeOrigin: true,
"pathRewrite":{
"^/api": ""
}
}
},
request
cityInfo(cityId){
axios.get("/api/"+cityId+".html")
.then((data)=>{
console.log(data.data)
})
}
Note, remember to reboot once .
In general, we allow the backend to allow cross-domain.
For example, java
the springboot
in contoller
the class mark @CrossOrigin(value = "*")
, and so many ways.