1, the preface
- We’ve already shown how to create a React project, including basic routing configuration, less, and UI usage.
- We’ll show you how to use AXIos to implement front – and back-end interactions in React. I covered this in detail in a previous article: Axios and secondary encapsulation work in much the same way.
2. Dependencies and configuration
- Install dependencies
cnpm i -S qs axios
Copy the code
- Create a new API folder under New SRC. The configuration is basically the same as before with axiOS and secondary encapsulation, with some modifications.
import axios from 'axios'
import qs from 'qs'
let fetch = axios.create({
baseURL: "http://localhost:3333", / / here is the local express to start the service address a timeout: 5000 / / request timeout}) fetch. Interceptors. Request. Use (config = > {if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
if(typeof(config.data) ! = ='string' && config.headers['Content-Type']! = ='multipart/form-data') {
config.data = qs.stringify(config.data)
}
}
return config
}, error => {
Promise.reject(error)
})
fetch.interceptors.response.use(async data => {
return data
}, error => {
if (error.response) {
if (error.response.status === 500) {
console.log('Server error, please contact administrator.')}return Promise.reject(error.response.data)
} else {
return Promise.reject(error)
}
})
export default fetch
Copy the code
- Create a new index.js file. Here we simulate two interfaces. Menu data for login verification and retrieval to the console, jump to the corresponding console (more on that later)
import fetch from './fetch'// example gets a json simulation of the dataexport function apiGetData() {
return fetch({
url: '/api/data/menu-list',
method: 'get'})} // Login verificationexport function apiLogin(params) {
return fetch({
url: '/api/login/validate',
method: 'get',
params
})
}
Copy the code
3. Use it on the page
- Let’s take the login page and the console page for example. Create a login page, configure routes, and click the login button on the home page.
import { apiLogin } from '@/api';
Copy the code
Create the React project
conclusion
- This article describes how to encapsulate and use AXIos in React. The on-demand reference to Axios in VUE works in the same way as secondary encapsulation.
- A brief introduction to page layout with and without UI.
- Redux and other parts will continue to be updated, gradually forming a completed project.