1. Create request.js under SRC and utils
Create a db.json file in pubilc with the following contents:
import axios from 'axios'/ / manually create a axios object, reference: https://github.com/axios/axios#creating-an-instanceConst request = axios. Create ({/ / request configuration reference: https://github.com/axios/axios#request-config BaseURL + write the URL when sending the request, such as get()'/test'), and finally send the request: /dev-api/test
// baseURL: '/dev-api',
baseURL: '/', the timeout: 5000 / / request timeout}) / / add interceptors / / request intercept request. Interceptors. Request. Use (config = > {/ / before sending a request to doreturnConfig},error=>{// request the wrong thing to doreturnPromise. Reject (error)}) / / response to intercept the request. The interceptors. Response. Use (response = > {/ / response before successreturnResponse},error=>{// What to do after the response failedreturn Promise.reject(error)
})
exportDefault Request // Export axios objectsCopy the code
2. Create an API folder under SRC and create a test.js file in the API folder
The contents of the test.js file are as follows:
import request from ".. /utils/request"// Import request file // Default path const BASE_URL="http://localhost:8888/"Request. Get (BASE_URL+"db.json").then(res=>{console.log(res)}).catch(error=>{console.log(error)})type:'get',
url:BASE_URL+'db.json'
}).then(res=>{
console.log(res)
}).catch(error=>{
console.log(error)
})
export default {
getList() {return request({
type:'get',
url:BASE_URL+'db.json'}}})Copy the code
3. Use in components
// Start with importtest from ".. /api/test"// Call use in the lifecyclecreated(){
this.fetch()
},
methods:{
frtch(){
test.getList(),then(res=>{
console.log(res)
}).catch(error=>{
console.log(error)
})
}
}
Copy the code