先安裝node.js和npm,這個不用說了,直接在創建vue項目,然后實踐一下跨域訪問。
如果npm安裝較慢,可安裝淘寶鏡像,執行下面命令:
npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install cnpm -g
1.全局安裝vue-cli:
npm install -g vue-cli
2.全局安裝webpack:
npm install -g webpack
3.初始化項目:
vue init webpack axios_cors(文件名稱)
4.切換到項目文件目錄下,安裝axios:
cd axios_cors
npm install axios
Ps.這里只需要安裝axios,microsoft.aspnetcore.cors是服務端支持跨域請求所需要安裝的包,npm里並沒有這個包
5.跨域訪問:
配置代理:config--》index.js
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中請求代碼:
<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>
頁面結果:
/****************************我是可愛的分割線********************************/