Vue跨域访问,axios&cors

Vue跨域访问,axios&cors,第1张

Vue跨域访问,axios&cors

安装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>

页面结果:

/****************************我是可爱的分割线********************************/

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/587409.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存