vue+.netcore webapi前后端分离跨域请求配置

1.安装http库-axios(axios 是一个基于 promise 的 HTTP 库):

npm install --save axios vue-axios    // npm安装

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

axios.defaults.baseURL = 'http://localhost:50538';// 配置接口地址

Vue.prototype.axios = axios;    // 改写vue的原型属性

2.axios使用:

    在vue组件中:

methods: {
        getTitleInfos() {
            this.axios
                .get("/api/values")
                .then(res => {
                    console.log("res",res);
                })
                .catch(err=>{
                    console.log("err",err);
                })
        }
    },
created() {
    this.getTitleInfos();
},

 前端配置完成。

3..netcore webapi配置

在startup.cs中更新配置:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            //配置跨域处理
            services.AddCors(options =>
            {
                options.AddPolicy("any", builder =>
                {
                    builder.AllowAnyOrigin() //允许任何来源的主机访问
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();//指定处理cookie
                });
            });
        }

在对应的接口类或者方法上添加:

[Route("api/[controller]")]
[EnableCors("any")]    // 刚刚添加的配置
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }

4.验证:

刷新页面,控制台输出请求结果:

猜你喜欢

转载自blog.csdn.net/Hello_JayJay/article/details/82966970