• <十一>请求 axios


    1、vue 发起请求,用的是axios。先安装一下

    npm install axios

     2、在main.js中注册全局的axios.

    import Vue from 'vue'
    import App from './App'
    import router from './router'
    import store from './store'
    import axios from 'axios'
    
    Vue.config.productionTip = false
    Vue.prototype.axios = axios
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      store,
      components: { App },
      template: '<App/>'
    })

    3、修改12345.vue的界面代码,点击按钮触发api调用

    <template>
    <div>
     <button @click="changeInfo">点击</button>
      <div class='hello'>{{msg}}</div>
    </div>
    </template>
    
    <script>
    export default {
      name: '12345',
      data () {
        return {
          msg: ''
        }
      },
      methods: {
        changeInfo () {
          this.axios.get('http://localhost:5000/weatherforecast').then(response => {
            this.msg = response
            console.log(response)
          })
        }
      }
    }
    </script>

    4、用.netcore3.1建一个api,默认最简单的api就好了。

     5、点击按钮,看下结果,出现了跨域的错误

     6、给api添加跨域处理,在startup类中添加跨域处理,app.usecors的位置要在UseAuthorization后面,不然会报错

     public void ConfigureServices(IServiceCollection services)
            {
                
                services.AddControllers();
               // 添加cors 服务 配置跨域处理
                services.AddCors(options =>
                {
                    options.AddPolicy("any", builder =>
                    {
                        builder.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
                        .AllowAnyOrigin(); //允许任何来源的主机访问
                    });
                });
            }
     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
               
                app.UseRouting();
                app.UseAuthorization();
                app.UseCors("any");
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }

    7、重新编译一下,点击按钮,看api返回的数据能否正常显示。

    8、上面例子是get调用,下面改造一下使用post

    后端新增一个post接口。

      [HttpPost]
            public IEnumerable<WeatherForecast> Post(string Name)
            {
                var rng = new Random();
                return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = rng.Next(-20, 55),
                    Summary = Name+":"+ Summaries[rng.Next(Summaries.Length)]
                })
                .ToArray();
            }

    前端换成post

    methods: {
        changeInfo () {
          this.axios.post('http://localhost:5000/weatherforecast', {Name: 'Aiden'})
            .then((response) => {
            this.msg = response
            })
            .catch((error) => {
              console.log(error)
            })
          // this.axios.get('http://localhost:5000/weatherforecast').then(response => {
          //   this.msg = response
          //   console.log(response)
          // })
        }
      }
    }

    重新运行后查看情况

     出现上述错误了,原因是请求头没有添加内容的类型。

    在post中,指定content-type

     this.axios.post('http://localhost:5000/weatherforecast', {Name: 'Aiden'}, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})

    再点击就可以了。

    9、将每个调用接口都抽取到相应的js 去,比如获取用户的就放到user.js里,这样更方便维护。这我就不讲了,跟状态管理一样,新建一个api文件夹,然后新建js,引入js。

  • 相关阅读:
    iOS 制作view渐变的效果CAGradientLayer
    iOS应用架构谈 view层的组织和调用方案
    xcode8 iOS10 log太多
    iOS 10 UserNotifications 框架解析
    iOS UITableViewCell 左滑删除时,修改删除按钮背景颜色,默认是红色的
    给self.navigationItem.rightBarButtonItem设置字体颜色
    iPhone屏幕尺寸、分辨率及适配
    iOS 判断输入是否全是空格
    ios 修改UItableviewcell点击时的颜色
    ios 播放语音(文字转语音) 播放音频文件 振动
  • 原文地址:https://www.cnblogs.com/choii/p/15684258.html
Copyright © 2020-2023  润新知