先安裝node.js和npm,這個不用說了,直接在建立vue項目,而後實踐一下跨域訪問。vue
若是npm安裝較慢,可安裝淘寶鏡像,執行下面命令:node
npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install cnpm -g
1.全局安裝vue-cli:webpack
npm install -g vue-cli
2.全局安裝webpack:ios
npm install -g webpack
3.初始化項目:web
vue init webpack axios_cors(文件名稱)
4.切換到項目文件目錄下,安裝axios:vue-cli
cd axios_cors
npm install axios
Ps.這裏只須要安裝axios,microsoft.aspnetcore.cors是服務端支持跨域請求所須要安裝的包,npm裏並無這個包npm
5.跨域訪問:json
配置代理:config--》index.jsaxios
module.exports = { dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/apis': { target:'http://t.weather.sojson.com/api',//請求域名 //secure: false, // 若是是https接口,須要配置這個參數 changeOrigin:true,//若是是跨域訪問,須要配置這個參數 pathRewrite:{ '^/apis': '/' } } }, ………… } }
HelloWorld.vue中請求代碼:api
<template> <div class="hello"> <h1>{{ msg }}</h1> <h2>跨域請求天氣</h2> <ul v-for="item in data" :key="item.id"> <li>{{item}}</li> </ul> </div> </template> <script> //引入axios import axios from "axios"; export default { name: "HelloWorld", data() { return { msg: "請求成功", data: null }; }, created() { //建立實例時設置配置的默認值 const httpHandler = axios.create({ headers: { "Content-Type": "application/json;charset=utf-8" }, //即將被髮送的自定義請求頭 withCredentials: true //表示跨域請求時是否須要使用憑證
}); let uri = "apis/weather/city/101030100"; httpHandler .get(uri) .then(result => { console.log(result); this.data = result; }) .catch(error => { console.error(error); }); } }; </script>
頁面結果:
/****************************我是可愛的分割線********************************/