Network request review. We have contacted some before. Ajax and jQuery encapsulate one based on XHR objects. We have also contacted a network request and request object in our applet. In React, I also touched a Fetch object. In Vue, we have a better scheme to cooperate with Vue: Axios. Of course, at the beginning of Vue, the official website maintained a network request Vue resource, but it is not recommended at present.
Axios
Axios is a promise based HTTP library that can be used in browsers and node JS.
Features
Create XMLHttpRequests from the browser
From node JS create http request
Promise API supported
Intercept requests and responses
Convert request data and response data
Cancel request
Automatically convert JSON data
Client support defense XSRF
install
npm install axios
bower install axios
Introduce usage
Global configuration
import axios from "axios" Vue.prototype.$axios = axios; this.$axios.get("http://iwenwiki.com/api/blueberrypai/getChengpinDetails.php") .then(res =>{ console.log(res.data); })
Local use
import axios from "axios" export default { name: 'HelloWorld', props: { msg: String }, mounted(){ axios.get("http://iwenwiki.com/api/blueberrypai/getChengpinDetails.php") .then(res =>{ console.log(res.data); }) } }
Request mode example
Get request
// Create a request for the user with the given ID axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // Alternatively, the above request can do so axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Post request
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Parameter precautions: the post request parameter requires a string type, such as name=iwen@age=20. Based on this, we need to convert the passed parameters through QueryString, QS stringify({})
Concurrent request
function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete }));
Configured defaults / defaults
Global axios default
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Interceptor
// Add request interceptor axios.interceptors.request.use(function (config) { // What to do before sending the request return config; }, function (error) { // What to do about request errors return Promise.reject(error); }); // Add response interceptor axios.interceptors.response.use(function (response) { // Do something about the response data return response; }, function (error) { // Do something about response errors return Promise.reject(error); });
Design principles
For the network request, it is not a one-time application, but runs through the whole application. Based on this, we need to encapsulate the network request so that we can better call it. And because there are many network requests, we should deal with and plan the network requests uniformly when we use them.
Encapsulate network requests
Unified processing of network requests
Cross domain processing
development environment
The environment in which we write code is called the development environment
Cross domain solutions:
Proxy proxy
It can only solve the cross domain in the development environment. After going online, this cross domain will no longer take effect
Two scenarios are addressed:
1. Background developers have no time to deal with cross domain issues
2. Our own analog data server, such as Mock, generates cross domain
Example code:
We need to create a file in the root directory of the project: Vue config. js. vue.config.js is an optional configuration file. If this file exists in the root directory of the project (at the same level as package.json), it will be automatically loaded by @ Vue / cli service. You can also use package The Vue field in JSON, but note that this writing method requires you to write in strict accordance with the JSON format.
production environment
The environment to be accessed by users in the browser after packaging and going online
npm run build: run this command to package the project directly.
In the browser, the only code that can run is HTML, CSS, JavaScript and resource files, such as Image
Cross domain solutions:
CORS background cross domain solution
Take effect in real time, regardless of development or production environment
[Tencent document] question bank
(it contains a lot of web front-end and back-end knowledge)