zoukankan      html  css  js  c++  java
  • 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>

    页面结果:

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

  • 相关阅读:
    为什么hive表有数据,但count(*)返回0
    数仓建设时,要建历史表,用于保存历史数据,用于日后出问题时,起修复数据的作用。按日期分区,每天都把所有的数据存到当天的分区里
    get_json_object用以获取json类型的字段的值
    str_to_map语句,字符串类型变map类型
    按更新时间取最新记录
    hive临时表
    数仓分层
    次日留存、七日留存
    转义
    数据库三范式
  • 原文地址:https://www.cnblogs.com/merryan-share/p/11010597.html
Copyright © 2011-2022 走看看