vue 에서 axios 를 사용 하 는 가장 자세 한 튜 토리 얼

20885 단어 링크
vue 에서 axios 를 사용 하 는 가장 자세 한 튜 토리 얼
https://www.cnblogs.com/nogodie/p/9853660.html
전제조건:vue-cli 프로젝트 설치:
npm
npm

main.js 에서 가 져 오기:
//   axios,       
import axios from 'axios';
Vue.prototype.$axios = axios;
import QS from 'qs'
Vue.prototype.qs = QS;

봉 인 된 axios,가 져 가 고 전송 하지 않 습 니 다.(main.js 동급 디 렉 터 리 에 https.js 파일 을 만 들 고 아래 코드 를 복사 하여 붙 여 넣 으 면 인터페이스 주 소 를 바 꾸 면 사용 할 수 있 습 니 다)
import axios from 'axios'
import qs from 'qs'

axios.defaults.timeout = 5000;                        //    
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';        //     
axios.defaults.baseURL = '';   //      

//POST     (       )
axios.interceptors.request.use((config) => {
    //           
    if(config.method  === 'post'){
        config.data = qs.stringify(config.data);
    }
    return config;
},(error) =>{
    console.log('     ')
    return Promise.reject(error);
});

//      (       )
axios.interceptors.response.use((res) =>{
    //        
    if(!res.data.success){
        return Promise.resolve(res);
    }
    return res;
}, (error) => {
    console.log('    ')
    return Promise.reject(error);
});

//    Promise(  post  )
export function fetchPost(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(response => {
                resolve(response);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}
////    Promise(  get  )
export function fetchGet(url, param) {
    return new Promise((resolve, reject) => {
        axios.get(url, {params: param})
            .then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
            .catch((error) => {
                reject(error)
            })
    })
}
export default {
    fetchPost,
    fetchGet,
}

개발 환경 은 일반적으로 도 메 인 을 넘 어 도 메 인 문 제 를 해결 해 야 합 니 다(프 록 시 설정).vue-cli 3.0 은 package.json 동급 디 렉 터 리 에 vue.config.js 파일 을 새로 만 들 고 아래 코드 를 추가 합 니 다.다른 버 전 은 프로필 의 devserver 가입 코드 를 찾 습 니 다.
module.exports = {
    //axios   ,  axios    
    baseUrl: '/',
    devServer: {
        proxy: {
            '': {
                target: 'http://192.168.0.108:8090',
                changeOrigin: true,
                ws: true,
                pathRewrite: {

                }
            }
        }
    }
}

수정 후 프로젝트 설정 을 다시 시작 하 는 것 을 기억 하 십시오.
그리고 수확 할 때 가 되 었 습 니 다.요청 할 vue 모듈 에서 가 져 오고 사용 합 니 다.
import https from '../https.js'   //         

//       ==================
            loginPost: function () {
                let params ={'username': 'admin', 'password': 'admin123', 'rememberMe': 'true','isMobile':'1'}
                https.fetchPost('/login',params ).then((data) => {
                    this.base.token = data.data.token    
                    // console.log("this.base.tokenthis.base.token",this.base.token)
                    this.indexPost2(this.rres)
                }).catch(err=>{
                        console.log(err)
                    }
                )
            },
            indexPost2:function (date) {
                var this_ = this
                this_.check = false
                var jobj ={data:{'menuDate': date,'token':this.base.token}}
                let string  = JSON.stringify(jobj)
                let params = {dailyInfo:string}
                https.fetchPost('/meals/mobile/getDailyMenuByDate', params)
                .then((data) => {
                    this_.base.indexData = data
                    this_.check = true
                    // console.log('thenthenthenthen',data)
                })
                .catch((err)=>{
                    console.log(err)

                })
            },
            // ================================================
        },

좋은 웹페이지 즐겨찾기