vue代理和跨域問題的解決
一、安裝vue-resource插件
cnpm install vue-resource --save
在根目錄下的package.json檢查一下插件的版本
在rourer-index.js下引入文件
import Resource from 'vue-resource' Vue.use(Resource)
引入vue-resource后,可以基于全局的Vue對象使用http,也可以基于某個Vue實(shí)例使用http 參考鏈接
二、安裝axios插件
cnpm install --save axios
在后臺服務(wù)文件(server.js)中引入
var axios = require('axios')
新建一個公共Js文件,用于存放httpserver
import axios from 'axios' // 引入axios插件 export function getHttp (url, callFun) { //get請求方法 axios.get(url).then(callFun) .catch(function(err){ console.log(err) }) }
三、proxy代理
在config-index.js
文件下找到proxyTable
設(shè)置代理
例如我的vue項(xiàng)目鏈接是 localhost:8080 后臺數(shù)據(jù)地址是 localhost:8081/api/seller(端口不一樣)
proxyTable: { '/api': { target: 'http://localhost:8081', changeOrigin: true, pathRewrite: { '^/api': '/api' // pathRewrite方法重寫url, 這樣配置出來的url為http://localhost:8081/api/seller // '^/api': '/' // pathRewrite方法重寫url, 這樣配置出來的url為http://localhost:8081/seller } } }
四、數(shù)據(jù)調(diào)用
在想調(diào)用數(shù)據(jù)的vue頁面中寫入如下代碼
js部分
<script> import {getHttp} from '../static/js/httpserver.js' export default { data () { return { seller: {} } }, methods: { shangjia: function () { let url = '/api/seller' getHttp(url, function (res) { res = res.data console.log(res) }) } } } </script>
html部分
<template> <div id="app"> <div @click='shangjia()'><router-link to='/seller'>商家</router-link></div> <router-view></router-view> </div> </template>
推薦可以模擬數(shù)據(jù)的網(wǎng)址
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue2 Vue-cli中使用Typescript的配置詳解
Vue作為前端三大框架之一截至到目前在github上以收獲44,873顆星,足以說明其以悄然成為主流。下面這篇文章主要給大家介紹了關(guān)于Vue2 Vue-cli中使用Typescript的配置的相關(guān)資料,需要的朋友可以參考下。2017-07-07antd的select下拉框因?yàn)閿?shù)據(jù)量太大造成卡頓的解決方式
這篇文章主要介紹了antd的select下拉框因?yàn)閿?shù)據(jù)量太大造成卡頓的解決方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10