In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "how to elegantly implement the front-end request Mock". The editor shows you the operation process through the actual case, the operation method is simple and fast, and the practicality is strong. I hope this "how to elegantly implement the front-end request Mock" article can help you solve the problem.
Background
In the daily work of our front-end, we inevitably need to request the back-end interface to obtain data for page rendering. At this time, the development of our front-end static pages and the corresponding logical processing are closely related to the back-end interface. Therefore, most of the time in the early stage of new requirements, we need to unify an interface document to serve as guidance and constraints for their respective development.
After defining the input and return parameters of the interface, we can develop our own mock data at the front end. For example, if we have a defined interface for querying the list of goods, we can naturally write the following code according to the interface document.
/ / define api
Const getProducts = () = > {
Return axios.get ('/ products')
}
/ / used in components
GetProducts (). Then (res= > {
This.productList = res.data
})
But at the beginning, the back end often only defines an interface format and does not implement the business logic, or it is not deployed. In order to make the page have data to facilitate development, we may mock in the following two ways
Modify the part that defines api
Const getProducts = () = > {
Return Promise.resolve ([
{id:001,name:' goods 1'}
])
}
Modify the calling part
GetProducts (). Then (res= > {
/ / this.productList = res.data
}). Finally () = > {
This.productList = [
{id:001,name:' goods 1'}
]
})
We can see that either way, we have to modify the code related to the interface, and when the interface is really available, we have to delete this part of the useless mock code. If there are dozens of interfaces, the repetitive workload is large, and it is easy to miss. Next, let's try how to elegantly implement the front-end mock.
Practice
Because the company's projects are generally based on vue, the next two solutions are introduced based on the projects built in vue/cli version 4.x (react is the same, just configure webpack), and the mainstream axios is used in http requests.
Option 1 uses the adpter of axios
As an excellent http library, axios is compatible with sending http requests in both browser and node environments. The core is that its built-in adpter module uses XMLHttpRequest on the browser side according to the running environment, initiates requests in the node environment using its built-in http, and supports the configuration of custom adpter.
From the perspective of the scenario, whether we need to use mock when developing locally is obviously a globally controllable operation, which can be easily switched on and off, and the most appropriate way is to distinguish between scripts.
Add dev:mock script, distinguish dev, and enable global mock
/ / package.json
"scripts": {
"dev": "vue-cli-service serve"
"build": "vue-cli-service build"
"dev:mock": "cross-env IS_MOCK=true vue-cli-service serve"
}
Cross-env helps us deal with compatibility issues by injecting IS_MOCK variables into process.env
Modify webpack configuration, omitting other irrelevant configurations
/ / vue.config.js
Const IS_MOCK = process.env.IS_MOCK = = 'true' / / true when running dev:mock
Module.exports = {
/ / use webpack definePlugin to inject global variables
ChainWebpack: config = > {
Config.plugin ('define'). Tap (args= > {
Args [0] .is _ MOCK = IS_MOCK
Return args
})
}
}
Add mock profile
Module.exports = {
'/ products': {
Code:0
Data: [
{id:001,name:' goods 1'}
]
Message:'success'
}
}
Encapsulate axios instance
Import axios from "axios"
/ / read mock configuration
Const mockMap = require ("xxxxxx/mock.js"); / / mock profile path
Var instance = axios.create ({
Adapter: (config) = > {
/ / match to the current url in the mock configuration and enable mock to enable custom adpter
If (mockMap [config.url] & & IS_MOCK) {
Return Promise.resolve ({
Data: mockMap [config.url]
Status: 200
})
} else {
/ / otherwise, the default adapter processing is called, and the custom adapter needs to be deleted, otherwise there will be an endless loop.
Delete config.adapter
Return axios (config)
}
}
})
Export default instance
Define the axios instance after api adopts configuration
/ / api.js
Import instance from 'xxxx' / / axios instance path
Export const getProducts = () = > {
Return instance.get ('products')
}
Used in the component
Import {getProducts} from 'api.js'
GetProducts (). Then (res= > {
This.productList = res.data
})
After using this scheme, you only need to maintain the mock.js file and configure the corresponding contents of the interface document to realize the local development request mock. You can run dev or dev:mock to decide whether to enable mock.
* * this mode is similar to the way the definition of api is modified above to implement mock, which is convenient in that it can be handled globally and does not actually send http requests.
Option 2: proxy + express
Although scenario 1 implements a simple mock function, there are actually a few unreasonable points to think about:
No http request was actually sent, and the whole link of the request was not simulated as realistically as possible.
Depending on the axios library, it is not explored whether other http libraries can be implemented and whether they are as portable as axios, so the extensibility is poor.
Functional coupling, mock as an additional functional module, embedded in the axios to deal with, will make axios become slightly bloated
Based on the above problems, we have the idea of using express to start a proxy server to receive requests from our front-end applications for mock-related processing and to simulate a complete closed-loop http request.
First, create a new server.js file under the root of the project to write the code for our proxy server
Const express = require ("express")
/ / introduce mock configuration file
Const mockMap = require (". / mock")
Const app = express ()
App.use (express.json ())
App.all ("*", requestFilter, async (req, res, next) = > {
Const {path} = req
Res.send (mockmap [path])
})
/ / corresponding to the settings in webpack prxoy, you can set an unoccupied port at will.
App.listen ("3306", () = > {
Console.log ("serve is running at port 3306")
})
Easy to understand, that is to listen to port 3306, intercept all requests and return mock data
Modify the proxy configuration of webpack so that when running the mock script, the request is called to our proxy server, omitting the rest of the irrelevant configuration
/ / vue.config.js
Const IS_MOCK = process.env.IS_MOCK = = 'true' / / true when running dev:mock
Module.exports = {
DevServer: {
/ / …
Proxy: {
/ / all requests that match / api will be forwarded to target
'/ api': {
/ / set target to the local proxy service address when mock is enabled, where port 3306 is consistent with the listening port in serve
Target: IS_MOCK? 'http://localhost:3306/': 'xxxxx'
Ws: true
ChangeOrigin: true
PathRewrite: {
'^ / api':''
}
}
}
}
}
Modify the code instance.defaults.baseURL = "/ api" that created the axios instance above, and set the baseURL of all requests so that the proxy configuration matches all requests
After completing the above configuration, we restart the front-end application and start our server code to use the mock function.
We can modify the script to make it easier to start the serve service automatically when we turn on the mock function
/ / package.json
"scripts": {
"dev": "vue-cli-service serve"
"build": "vue-cli-service build"
"dev:mock": "cross-env IS_MOCK=true vue-cli-service serve & node serve.js"
}
In fact, at this point, the functions of mock are already available, and we can expand them based on the existing code and our own needs.
Development
I expanded a little bit when I used it in the project to provide you with a reference for expansion.
Modify mock configuration file
Module.exports = {
'/ products': {
Code:0
Data: [{
Id:1
Name:' Commodity 1'
}]
Message:'success'
Config: {
Method:'GET'
Delay: 1000
Validator: (request) = > {
Const error = {
Status:400
Msg:', please check whether the parameter is valid!'
}
Const success = {
Status:200
Msg:'success'
}
/ / assume that the request requires a required parameter timestamp
Return request.query.timestamp? Success: error
}
}
}
}
Additional config fields are added to make some differential configuration, such as specifying response delay 1000ms required parameter check, etc.
Modify serve side code
Const express = require ("express")
Const mockMap = require (". / mock")
Const app = express ()
App.use (express.json ())
/ / request filter
Const requestFilter = (req, res, next) = > {
Const {path,method} = req
/ / set the corresponding header to deal with Chinese garbled
Res.set ('Content-Type',' text/plain')
/ / 404 pre-filtering
If (! MockMap [path]) {
Res.status (404). End ()
}
/ / request methods do not match and filter in advance
If (method! = = mockmap [path] .config? .method?? 'GET') {
Res.status. End ('Please check whether the request method is correct!' )
}
/ / Custom check rules mismatch filtering
If (mockmap [path] .config & & mockmap [path] .config.validator) {
Const data = mockMap [path] .config.validator (req)
If (data.status! = 200) {
Res.status (data.status). End (data.msg)
}
}
SetTimeout () = > {
Next ()
}, mockmap [path] .config? .delay? 0)
}
App.all ("*", requestFilter, async (req, res, next) = > {
Const {path} = req
/ / remove config field
Const {code,data,message} = mockMap [path]
Res.send ({code,data,message})
})
App.listen ("3306", () = > {
Console.log ("serve is running at port 3306")
})
This is the end of the introduction to "how to elegantly implement the front-end request Mock". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.