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 這個屬性寫死的緣故吧。
如果有前端大佬解釋下不勝感激。