Check whether the Vue connects to the rear end successfully
Using axios API
You can create a request by passing the configuration to AXIOS and determine whether the connection is successful based on the data axios receives.
Go to the Vue project and add the following new code to the main.js file to send the request when the page is refreshed and print the relevant data on the console.
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios' / / introduce axios
import Qs from 'qs' // Use the qs tool to handle the parameters, process the parameters of the send request, serialize the string
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>',})// Submit data
axios({
url: '/api/aaa/bbb'.// Address of the back-end interface
method: 'post'.data: {
username: "hello".password: "world"
},
transformRequest: [function (data) {
data = Qs.stringify(data);
returndata; }].headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
dataType: "json"
})
.then(res= > {
console.log("Connection successful"); // Print an extra hint here, just to be more intuitive
console.log(res); // The res is the data returned from the back end. If the connection is successful, you can print the RES.
})
.catch(function (error) {
console.log("Connection failed"); // same as above
console.log(error); // If the connection fails, an error message is thrown.
});
Copy the code
The connection is successful
When the connection is successful, the data received by AXIOS is processed by THEN and the connection and received data can be printed out.
The connection fails
When the connection fails, the AXIos request goes into error processing. The CATCH will process the thrown error message and print out the failed connection and related error information.