vue本地呼叫伺服器介面跨域問題,也就是localhost:8080呼叫http://10.100.55.110:8000/api/userauth的跨域問題
其實,只需要配置vue的config/index.js檔案就行了,其他的axios的baseURL不用管,不寫。程式碼如下:
// see http://vuejs-templates.github.io/webpack for documentation.
'use strict'
var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/ctx': {// 替換target中的請求地址,也就是說以後你在請求http://10.100.55.110:8000/api/userauth/這個地址的時候直接寫成/ctx即可。
target:'http://10.100.55.110:8000/api/userauth', // 你請求的第三方介面
changeOrigin:true, // 在本地會建立一個虛擬服務端,然後傳送請求的資料,並同時接收請求的資料,這樣服務端和服務端進行資料的互動就不會有跨域問題
pathRewrite:{ // 路徑重寫,當路徑中有ctx時,'^/ctx':'/ctx',路徑中的ctx轉為target中的地址,後面帶有'/ctx';路徑中沒有ctx時,'^/ctx':'',路徑中的ctx只轉為target中的地址,後面不帶'/ctx'
'^ /ctx': ''
}
}
},
cssSourceMap: false
}
}
然後,登入介面components/login.vue程式碼這樣寫:
<template>
<div id="login">
<span>使用者名稱:</span><input type="text" v-model="rule.userName">
<span>密碼:</span><input type="password" v-model="rule.passWord">
<button @click="dl()">登入</button>
</div>
</template>
<script>
import {b64_md5} from '../b64_md5/md5.js';
export default {
name:'login',
data(){
return{
rule:{
userName:'',
passWord:''
}
}
},
methods:{
dl:function(){
var pata={"userName":this.rule.userName,"password":b64_md5(this.rule.passWord)};
// console.log(pata);
var url="/ctx/verify/loginByPwd";
this.$api.post(url,pata).then(function(response){
console.log("response:"+response.status);
}).catch(function(error){
console.log("error:"+error);
});
}
}
}
</script>