版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011649691/article/details/82702830
使用jsonp可以跨域请求,但是jsonp只能够用get方式跨域。其他跨域方式大多都要服务器支持。
使用vue.js和axios能解决get/post方式的跨域。但需要vue.js/node.js的基础知识。具体操作如下:
1、使用vue-cli脚手架创建一个vue工程:
2、修改config/index.js文件,在proxyTable中添加代理项,添加内容后如下:
proxyTable: {
'/api': {
target: 'http://localhost:8076/',// 请换成你的地址
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
3、引入axios,例如在示例中的main.js引入:
import Vue from 'vue'
import App from './App'
import router from './router'
import Axios from 'axios'
Vue.prototype.$axios = Axios
Vue.prototype.HOME = '/api'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
3、在vue.js组件中使用axios跨域请求,示例中使用app.vue请求
<template>
<div id="app">
<img src="./assets/logo.png">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App',
created () {
var url = this.HOME + '/api/reader/borrowBooksAlone'
for(var i=0;i<2;i++){
this.$axios.post(url,{
"tags":["e004015065527bfb"],"identity":"738430142809510211","identityType":{"index":1,"desc":"读者证"}
},{
headers: {'Content-Type':'application/json','appKey':'XDEAFK3EPLIUOTRXBS1R','deviceId':'AHRF'}
}).then(res => {
console.log("res:"+res.data)
alert(res.data)
}).catch(error => { console.log("error:"+error) })
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
4、启动vue项目:
cd vue工程目录
npm run dev
5、在浏览器中访问即可:
localhost:8080/api/
6、注意:修改config/目录中的任何项目都需要重启vue工程才能生效。