Vue axios請求params&data 詳解

params是添加到url的請求字符串中的,一般用于get請求皱蹦。
data是添加到請求體(body)中的射众, 一般用于post請求。

1.先來說說params.

vue前端:

saveGenerateCollectName(this.saveCollectNameCons).then(res => {
                        console.log('res.status:  ' + res.status)
                        this.status = res.status
                        this.message = res.message
                        if(this.status == 0){
                            this.$message.success(`成功`)
                        }else {
                            this.$message.info(`失敗`)
                        }
                    }).catch(err => {
                        console.log('saveGenerateCollectName-this.message:  ' + this.message)
                        if(err.toString().indexOf('cancel') == -1){
                            this.$message.error(`服務(wù)器問題,刪除失敗,失敗原因為:${err}`)
                            return false;
                        }
                    });
                    

axios js部分
index.js

export  const saveGenerateCollectName = query =>{
    return request({
        // url:'/list-lib/uploadFileResult.json',
        // method:'get',
        url:'/collectList/saveGenerateCollectName',
        method: 'post',
        //data: {collectList:query}  //data 用@RequestBody來接收
         params: {collectList:query}  //params用@RequestParams 來接收
    }).catch(error => {
        // console.log('error:---   ' + JSON.stringify(error));
        // alert(typeof error)
    });

};

request.js

import axios from 'axios';

const service = axios.create({
    // process.env.NODE_ENV === 'development' 來判斷是否開發(fā)環(huán)境
    // easy-mock服務(wù)掛了乍炉,暫時不使用了
    // baseURL: 'https://www.easy-mock.com/mock/5e3633b162df5945932860ef/TEST1',
    baseURL:'http://localhost:8084/xt-demo',
    timeout: 50000,
    // headers:{'Content-Type':'application/x-www-form-urlencoded'}// 'multipart/form-data'   //  'application/x-www-form-urlencoded';
});

service.interceptors.request.use(
    config => {
        // console.log('config.method---:   ' + config.method);
        console.log('config.url---:   ' + config.url)
        console.log('config.data---:   ' + config.data);
        // console.log('config.params---:   ' + config.params);
        debugger
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            // console.log('response.data---:   ' + response.data.status)
            return response.data;
        } else {
            Promise.reject();
        }
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

export default service;

后端代碼

public Map saveGenerateCollectName(@RequestParam("collectList") String tempCollectList){
        Map result = new HashMap();
        String tempCollectList = map.get("collectList").toString();
        return result;
    }

}
2.在來說說data.

vue前端:

saveGenerateCollectName(this.saveCollectNameCons).then(res => {
                        console.log('res.status:  ' + res.status)
                        this.status = res.status
                        this.message = res.message
                        if(this.status == 0){
                            this.$message.success(`成功`)
                        }else {
                            this.$message.info(`失敗`)
                        }
                    }).catch(err => {
                        console.log('saveGenerateCollectName-this.message:  ' + this.message)
                        if(err.toString().indexOf('cancel') == -1){
                            this.$message.error(`服務(wù)器問題,刪除失敗,失敗原因為:${err}`)
                            return false;
                        }
                    });
                    

axios js部分
index.js

export  const saveGenerateCollectName = query =>{
    return request({
        // url:'/list-lib/uploadFileResult.json',
        // method:'get',
        url:'/collectList/saveGenerateCollectName',
        method: 'post',
        data: query  //data 用@RequestBody來接收
        // params: {collectList:query}  //params用@RequestParams 來接收
    }).catch(error => {
        // console.log('error:---   ' + JSON.stringify(error));
        // alert(typeof error)
    });

};

request.js

同上

后端代碼

@RequestMapping(value = "saveGenerateCollectName",method = RequestMethod.POST)
    public Map saveGenerateCollectName(@RequestBody Map<String,Object> map ){
//        String tempCollectList = map.get("collectList").toString();
        Map result = new HashMap();
        String status = "0";
        String message = "成功新建收藏夾";
        CollectList collectList = new CollectList();
        Map collectListMap = map;//JSON.parseObject(map, Map.class);
        collectList.setCollectName(collectListMap.get("newCollectName").toString());
        String tempTime = collectListMap.get("newCollectNameDate").toString();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateTime = null;
        try {
            dateTime = simpleDateFormat.parse(tempTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        collectList.setGenerateDate(dateTime);
        collectList.setLastUpdateDate(dateTime);
        CollectList collectResult = this.collectListService.insert(collectList);
        if(collectResult == null ){
            status = "1";
            message="新建收藏夾失敗";
        }
        result.put("status",status);
        result.put("message",message);

        return result;
    }

3.關(guān)于附件上傳的特別說明

vue前端:

uploadFiles(file){
                debugger
                let formData = new FormData();  //此處有坑,附件上傳必須用formData
                formData.set("file", file.file);  //后端是根據(jù)"file" 來進行取值(@RequestParam("file") 或者@RequestBody MultipartFile file)
                uploadFiles(formData).then(res => {
                    this.status = res.status
                    this.message = res.message
                    console.log('this.status:  ' + this.status)
                    // console.log('refs.length2:  ' + that.$refs.upload.$children[0].fileList.length)
                    // debugger
                    if (this.status == 0) {
                        // debugger
                        this.$message.success(`附件上傳成功`)
                    } else {
                        this.$message.info(`附件上傳失敗,失敗原因${this.message}`)
                    }
                }).catch(err => {
                    // debugger
                    console.log('uploadFiles-err:  ' + err)
                    if(err.toString().indexOf('cancel') == -1){
                        this.$message.error(`刪除失敗,失敗原因為:${err}`)
                        return false;
                    }
                });

el-upload 部分

<el-upload class="upload-demo"
                               ref="upload"
                               action=""
                               :http-request = "uploadFiles"
                               :multiple="true"
                               :accept="acceptFileType"
                               :limit="1"
                               :on-exceed="handleExceed"
                               :before-upload="beforeUpload"
                               :on-preview="handlePreview"
                               :on-remove="handleRemove"
                               :file-list="fileList"
                               :auto-upload="false">
                        <el-button size="small" type="text">點擊上傳</el-button>
<!--                        <label>點擊上傳</label>-->
<!--                        <div slot="tip" class="el-upload_tip">只能上傳.xls文件,且不超過1M</div>-->
                    </el-upload>

axios js部分
index.js

//附件上傳
export const uploadFiles = query => {
    return request({
        // url: '/list-lib/uploadFileResult.json',
        // method: 'get',
        url: '/fileList/uploadFiles',
        method: 'post',
        data:query   // 附件上傳只能用data 來傳數(shù)據(jù),后端用@RequestBody
       
    }).catch(error => {
        // console.log('error:---   ' + JSON.stringify(error));
        // alert(error)
    });
};

request.js

同上

后端代碼

@RequestMapping(value = "uploadFiles",method = RequestMethod.POST)
//    @PostMapping("uploadFiles")
//    RequestParam 用來取axios 中params&data 的值,RequestBody 用來去axios中data 的值
//    public Map uploadFiles(@RequestParam("file") MultipartFile file ) {
    public Map uploadFiles(@RequestBody MultipartFile file ) {
        Map resultMap = new HashMap();
        String status="0";
        String message="附件上傳成功";
        resultMap.put("status",status);
        resultMap.put("message",message);
        if (file.isEmpty()) {
            status = "1";
            message="上傳文件不能為空";
            resultMap.put("status",status);
            resultMap.put("message",message);
            return resultMap;
        }else{
        //上傳文件 相關(guān)邏輯
            String fileName = file.getOriginalFilename();
            File dest = new File(uploadPath+fileName);
            try {
                file.transferTo(dest);
                return resultMap;
            } catch (IOException e) {
                status="2";
                message="附件上傳失敗.";
                resultMap.put("status",status);
                resultMap.put("message",message);
                e.printStackTrace();
            }

            return resultMap;
        }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市滤馍,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌底循,老刑警劉巖巢株,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異熙涤,居然都是意外死亡阁苞,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進店門祠挫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來那槽,“玉大人,你說我怎么就攤上這事等舔∩Ь模” “怎么了?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵慌植,是天一觀的道長甚牲。 經(jīng)常有香客問我,道長蝶柿,這世上最難降的妖魔是什么丈钙? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮交汤,結(jié)果婚禮上雏赦,老公的妹妹穿的比我還像新娘。我一直安慰自己芙扎,他們只是感情好星岗,可當我...
    茶點故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著戒洼,像睡著了一般伍茄。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上施逾,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天敷矫,我揣著相機與錄音例获,去河邊找鬼。 笑死曹仗,一個胖子當著我的面吹牛榨汤,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播怎茫,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼收壕,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了轨蛤?” 一聲冷哼從身側(cè)響起蜜宪,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎祥山,沒想到半個月后圃验,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡缝呕,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年澳窑,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片供常。...
    茶點故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡摊聋,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出栈暇,到底是詐尸還是另有隱情麻裁,我是刑警寧澤,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布源祈,位于F島的核電站悲立,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏新博。R本人自食惡果不足惜薪夕,卻給世界環(huán)境...
    茶點故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望赫悄。 院中可真熱鬧原献,春花似錦、人聲如沸埂淮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽倔撞。三九已至讲仰,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間痪蝇,已是汗流浹背鄙陡。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工冕房, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人趁矾。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓耙册,卻偏偏與公主長得像,于是被迫代替她去往敵國和親毫捣。 傳聞我的和親對象是個殘疾皇子详拙,可洞房花燭夜當晚...
    茶點故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容