8 Mock.js installation and use
in the process of development, in order to make it easier for the front end to debug the interface alone, Mock.js is often used to intercept Ajax requests and return preset data. This section describes how to use Mock.js in a react project.
perform installation:
npm install mockjs --save
create a new mock.js under src, as follows:
import Mock from 'mockjs'
const domain = '/api/'
// Simulating the getData interface
Mock.mock(domain + 'getData', function () {
let result = {
code: 200,
message: 'OK',
data: 'test'
}
return result
})
then introduce mock.js:
into src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import { Provider } from 'react-redux'
import store from './store'
+ import './mock'
import './common/style/frame.styl'
...(summary)
it's so simple. In this way, when a / api/getData
is requested in a project, it is intercepted by Mock.js and the data written in mock.js is returned.
9 solve the cross-domain problem of local development
in the react development environment, port 3000 is started by default, while the back-end API service may be on port 80 of the machine, so cross-domain problems may occur during ajax requests. Reverse proxy can be implemented with the help of http-proxy-middleware tools.
perform installation:
npm install http-proxy-middleware --save-dev
create a setupProxy.js under src, as follows:
const proxy = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
'^/api',
proxy({
target: 'http://localhost',
changeOrigin: true
})
)
}
this code means that as long as the request address starts with "/ api", it will reverse proxy to the http://localhost domain name and solve the cross-domain problem! You can modify it according to the actual needs.
Note: after setupProxy.js is set, the project must be restarted before it takes effect.
10 other commonly used tools
- Axios-Ajax request tool
[official website] github.com/axios/axios
[installation command]
npm install axios --save
- better-scroll-Native scrolling experience tool for pages
[official website] ustbhuangyi.github.io/better-scro …
[installation command]
npm install better-scroll --save
- react-transition-group-CSS3 Animation combination tool
[official website] github.com/reactjs/rea …
[installation command]
npm install react-transition-group --save
- react-loadable-dynamic loading component tool
[official website] www.npmjs.com/package/rea …
[installation command]
yarn add react-loadable
11 Integrated Ant Design
Ant Design is a very useful front-end UI library, and many projects use Ant Design.
[official website]
this chapter integrates create-react-app with Ant Design after eject based on the above section.
Comments