1. Introducing Axios: When network requests to use Axios, first install the Axios dependency
npm i axios -S
For network requests, since it is necessary to judge various exceptions at each request, and then prompt the user, such as whether the request is successful or not, the reason for failure, etc. Considering that these judgments basically use duplicate codes, the network request can be encapsulated as a Vue plug-in for easy use. Since the encapsulated code is relatively long, it will not be posted here. Readers can view it on GitHub at https://github.com/lenve/vhr/blob/master/vuehr/src/utils/api.js 。 After configuration, import the encapsulated method in main.js and configure it as Vue's prototype. The code is as follows:
import { getRequest } from './ utils/api' import { postRequest } from './ utils/api' import { deleteRequest } from './ utils/api' import { putRequest } from './ utils/api' Vue.prototype.getRequest = getRequest; Vue.prototype.postRequest = postRequest; Vue.prototype.deleteRequest = deleteRequest; Vue.prototype.putRequest = putRequest;
After the configuration is completed, you can use this for any address that needs to use the network request XXX executes a network request. For example, to execute a login request, you can use this PostRequest (url, param) execution.
2. Configure request forwarding
Since the front-end project and back-end project are started under different ports, the front-end network requests cannot be sent directly to the back-end, so request forwarding needs to be configured. The configuration method is described below.
Modify the index.js file in the config directory, and modify the proxyTable. The code is as follows:
proxyTable: { //Configure HTTP request forwarding '/': { target: ' http://192.168.84.72:8080 ', changeOrigin: true, pathRewrite: { '^/': '' } }, //Configure WebSocket request forwarding '/ws/*': { target: 'ws://127.0.0.1:8082', ws: true } }
Two rules are configured here. The first is to configure HTTP request forwarding, and the second is to configure WebSocket request forwarding, which will be used in the instant messaging module of this project.