什么是跨域再沧?
一句話:你可以理解成尼夺,別人為了防止你直接訪問api,攻擊他們的服務(wù)器做的保護(hù)傘。
那么我們怎么解決訪問題炒瘸,去訪問別人的數(shù)據(jù)呢淤堵?
使用《vue-反向代理》
1.下載axios安裝https://github.com/axios/axios,我這里用的yarn顷扩,yarn真的超級好用
$ yarn add axios
npm 的用戶可以用如下
$ npm install axios
不同的終端不同的代碼大家可以直接在github中搜索axios查看安裝代碼
我們使用下面的代碼直接復(fù)制到vscode編譯器中
get
axios.get(‘你的API去掉com之前的內(nèi)容').then(function(response)
{// handle successconsole.log(response);})//打印返回結(jié)果
.catch(function(error){
// handle errorconsole.log(error);}) //捕獲異常
.then(function(){
// always executed}); //接下來執(zhí)行
舉個例子:axios拐邪。你的完整網(wǎng)站是:http://m.xxxxxxxxxxxxxxxxxxxxx.com/?/ajax/movieOnInfoList?token=
get里面放入:/ajax/movieOnInfoList?token=
post
axios.post('你的API去掉com之前的內(nèi)容',{firstName:'Fred',lastName:'Flintstone'})
.then(function(response){console.log(response);})
.catch(function(error){console.log(error);});
vue中請求
// vue中導(dǎo)入import
<script>
import axios from 'axios'
export default {
? mounted() {
? ?axios.get("/ajax/movieOnInfoList?token=")
? .then(function (response) {
? ? // handle success
? ? console.log(response);
? })
</script>
最后創(chuàng)建一個vue.config文件,位置要與package屎即。json平級庙睡,我們在vuecli的官方文檔中就可以查看到相關(guān)的說明,我們直接把代碼復(fù)制過來
module.exports = {
? devServer: {
? ? proxy: {
? ? ? '/ajax': { //這里你要設(shè)置在什么字符串中攔截代理技俐,白話文網(wǎng)站最好設(shè)置com結(jié)尾后面的字符串
? ? ? ? target: 'http://m.xxxxxxxxxxxxxxxxxxxxx.com', //里面設(shè)置為網(wǎng)站地址
? ? ? ? // ws: true,
? ? ? ? changeOrigin: true
? ? ? },
? ? ? // '^/foo': {
? ? ? // ? target: '<other_url>'
? ? ? // }
? ? }
? }
}
最后我們重啟一下服務(wù)器就可以查看到結(jié)果
你可以使用
npm run serve?
或者用
yarn serve