vue本身不支持發送AJAX請求,需要使用vue-resource、axios等插件實現
axios是一個基本Promise的HTTP請求客戶端,用來發送請求,也是vue2.0官方推薦的,同時不再對vue-resource進行更新和維護
axios發送AJAX請求
安裝axios
- npm install axios -S
基本用法
- axios([options])
- axios.get(url[,options]) 傳參方式:1.通過url 傳參 2.通過params選項傳參
- axios.post(url,data,[options]) axios默認發送數據時,數據格式是Request Payload(也就是對象傳入,后台接收json數據),並非我們常用的Form Data格式(字符串拼接參數的形式傳入),所以參數必須要以鍵值對形式傳遞,不能以json形式傳參,傳參方式:
- 自己拼接為鍵值對
- 使用transformRequest,在請求發送前將請求數據進行轉換
- 如果使用模塊化開發,可以使用qs模塊進行轉換
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>發送AJAX請求</title>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script src="js/vue-resource.min.js"></script>
<script>
window.onload=function(){
new Vue({
el:'#itany',
data:{
user:{
// name:'alice',
// age:19
},
uid:''
},
methods:{
send(){
axios({
method:'get',
url:'user.jsonaaa'
}).then(function(resp){
console.log(resp.data);
}).catch(resp => {
// console.log(resp);
console.log('請求失敗:'+resp.status+','+resp.statusText);
});
},
sendGet(){
// axios.get('server.php?name=tom&age=23')
axios.get('server.php',{
params:{
name:'alice',
age:19
}
})
.then(resp => {
console.log(resp.data);
}).catch(err => {
console.log('請求失敗:'+err.status+','+err.statusText);
});
},
sendPost(){
// axios.post('server.php',{
// name:'alice',
// age:19
// })
// axios.post('server.php','name=alice&age=20&') //方式1
axios.post('server.php',this.user,{
transformRequest:[
function(data){
let params='';
for(let index in data){
params+=index+'='+data[index]+'&';
}
return params;
}
]
})
.then(resp => {
console.log(resp.data);
}).catch(err => {
console.log('請求失敗:'+err.status+','+err.statusText);
});
},
getUserById(uid){
axios.get(`https://api.github.com/users/${uid}`)
.then(resp => {
// console.log(resp.data);
this.user=resp.data;
});
},
sendJSONP(){
//https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=a
this.$http.jsonp('https://sug.so.360.cn/suggest',{
params:{
word:'a'
}
}).then(resp => {
console.log(resp.data.s);
});
},
sendJSONP2(){
//https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&json=1&p=3&sid=1420_21118_17001_21931_23632_22072&req=2&csor=1&cb=jQuery110208075694879886905_1498805938134&_=1498805938138
this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{
params:{
wd:'a'
},
jsonp:'cb' //百度使用的jsonp參數名為cb,所以需要修改
}).then(resp => {
console.log(resp.data.s);
});
}
}
});
}
</script>
</head>
<body>
<div id="itany">
<button @click="send">發送AJAX請求</button>
<button @click="sendGet">GET方式發送AJAX請求</button>
<button @click="sendPost">POST方式發送AJAX請求</button>
<hr>
<br>
GitHub ID: <input type="text" v-model="uid">
<button @click="getUserById(uid)">獲取指定GitHub賬戶信息並顯示</button>
<br>
姓名:{{user.name}} <br>
頭像:<img :src="user.avatar_url" alt="">
<hr>
<button @click="sendJSONP">向360搜索發送JSONP請求</button>
<button @click="sendJSONP2">向百度搜索發送JSONP請求</button>
</div>
</body>
</html>
另外axios不是全局組件,需要使用時,在每個文件都要引入,如果想達到全局效果,可以在main.js用原型進行綁定Vue.prototype.$http=axios
Proxy代理
對於前后端分離模式下,前端請求后端存在跨域問題,除了后端主動設置允許跨域請求的類型,前端也可使用proxy代理來轉發請求實現跨域
項目准備
-
vue init webpack proxy-demo
-
cd proxy-demo
-
npm install
-
npm install axios -S
-
npm run dev
在下面文件下的proxyTable配置代理

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/flask-api': {//前端路由匹配模式
target: 'http://localhost:9001', //后端請求服務域名和端口
changeOrigin: true, //設置請求頭
pathRewrite: {
'^/flask-api': '/' //路徑重寫 前端/flask-api 對應 后端/
},
}
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: true, //運行npm run dev 打開瀏覽器
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
就拿login舉例,前端localhost:8080/flask-api/login --> 后端http://localhost:9001/login,而在用axios發送請求時,不用寫localhost:8080,直接寫/flask-api/login就可以了
<script>
import axios from "axios";
export default {
name: "App",
mounted() {
axios
.get("/flask-api/task/get")
.then(resp => {
console.log(resp.data);
})
.catch(err => {
console.log("request fail");
});
},
methods: {
send() {
axios
.post("/flask-api/task/get", { "hello": "hello" })
.then(resp => {
console.log('sucees')
// this.$message.success("success");
})
.catch(err => {
console.log(err);
console.log(err.status);
console.log(err.statusText);
console.log("request fail");
});
}
}
};
</script>
其他
axios本身並不支持發送跨域請求,需要使用vue-resource發送跨域請求
安裝
- npm install vue-resource -S
基本用法
使用this.$http發送請求
this.$http.get(url, [options])
this.$http.head(url, [options])
this.$http.delete(url, [options])
this.$http.jsonp(url, [options])
this.$http.post(url, [body], [options])
this.$http.put(url, [body], [options])
this.$http.patch(url, [body], [options])
