axios 獲取不到數據錯誤


1.問題:

打算學習下vue,但是vue-resource作者已經不更新了,並且大家都建議用axios來進行前后端交互,所以就從學習axios開始。

但是在使用 axios 的過程中,自己寫的接口竟然訪問不到,jquery可以訪問但是axios不能訪問。post也能訪問就是axios不能訪問。

axios.post('test',{})
.then(function (response){
    console.log('axios.post:');
    console.log(response.data);
})
.catch(function (error){
    console.log(error);
});

axios({
    url: 'test',
    method: 'post',
    responseType: 'json', // 默認的json
    data: {
        //'a': 1,
        //'b': 2,
    }
}).then(function (response) {
    console.log('axios:');
    console.log(response);
    console.log(response.data);
}).catch(function (error) {
    console.log(error);
});
$.ajax({
    type: 'POST',
    url: 'test',
    data: {},
    success: function(data) {
        console.log("ajax:");
        console.log(data);
    },
    error: function() {}
});

可以看到 axios 為null;

2.原因:

 單個字符串json沒有解析,直接返回的text格式。。。。 

    @RequestMapping(value="/test")
    public String test() {
        return "hello world!";
    }

3.解決:

把 responseType: 'json' 改成 responseType: 'text'

  即可。

但是 post 方法 和 jquery 就沒有這種煩惱,不管是 text  還是 json 都能直接判斷,可能是 responseType 這個屬性寫死的緣故吧。

如果有前端大佬解釋下不勝感激。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM