1. 程式人生 > >vue+.netcore webapi前後端分離跨域請求配置

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.驗證:

重新整理頁面,控制檯輸出請求結果: