zoukankan      html  css  js  c++  java
  • .net core webapi+vue 跨域访问

    最近在做一个前后端分离的示例,以下代码完美解决跨域的问题

    一、后端服务

    1.首先我们建一个.net core webapi的项目

    2.项目引用Microsoft.AspNetCore.Cors 包

    3.添加cors 服务

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
                //添加cors 服务
                services.AddCors(options =>//p.WithOrigins这里就是配置策略,允许访问的地址
            options.AddPolicy("Admin", p => p.WithOrigins("http://localhost:5000", "http://localhost:9528").AllowAnyMethod().AllowAnyHeader().AllowCredentials()) ); }

    4.配置Cors

      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseHsts();
                }
                //配置Cors
                app.UseCors("Admin");
                app.UseHttpsRedirection();
                app.UseMvc();
            }
    

    5.编写控制器

     [Route("api/[controller]")]
        [ApiController]
        public class GetDataController : ControllerBase
        {
            // GET api/values
            [HttpGet]
            [EnableCors("Admin")]
            public ActionResult<IEnumerable<string>> Get()
            {
                return new string[] { DateTime.Now.ToString() };
            }
    
            // GET api/values/5
            [HttpGet("{id}")]
            public ActionResult<string> Get(int id)
            {
                return "value";
            }
    
            // POST api/values
            [HttpPost]
            public void Post([FromBody] string value)
            {
            }
    
            // PUT api/values/5
            [HttpPut("{id}")]
            public void Put(int id, [FromBody] string value)
            {
            }
    
            // DELETE api/values/5
            [HttpDelete("{id}")]
            public void Delete(int id)
            {
            }
        }
    

      

    二、前段

    1.创建Vue前段项目,我这里是使用的是vue+element (自己百度创建)

    2.安装axios模块 npm install axios -g

    3.调用api

    export default {

    data() {
    return {
    msg:''
    }
    },
    methods: {
    onSubmit() {
    let _self=this;
    console.log(this.form)
    axios.get('http://localhost:5000/api/GetData')

    .then(function (response) {
    console.log(response);
    _self.msg=response.data;
    })
    .catch(function (error) {

    console.log(error);

    });
    }
    }
    }

      

  • 相关阅读:
    计算机网络精华知识总结01
    使用hexo创建github博客
    Android Toolbar样式定制详解
    我的PhoneGap安装配置经历
    APMServ5.2.6升级PHP
    WordPress网站更换老鹰主机详细操作
    Windows下的SVN环境搭建详解
    最新Android 出现Please ensure that adb is correctly located at问题的解决方法
    QSqlDatabase
    Qt Pro相关
  • 原文地址:https://www.cnblogs.com/zhurunlai/p/9774020.html
Copyright © 2011-2022 走看看