dotnet core webapi +vue 搭建前后端完全分離web架構(一)


 

架構

服務端采用 dotnet core  webapi

 

前端采用: Vue + router +elementUI+axios

 

 

                         

 

問題

使用前后端完全分離的架構,首先遇到的問題肯定是跨域訪問。前后端可能不在同個server上,即使前后端處在同個server上,由於前后端完全分離,

前后端使用的端口號也可能是不一樣的,所以必須解決跨域訪問。

 

具體實現

 

服務端

服務端使用的dotnetcore +webapi架構,支持cors非常簡單,只要引入Microsoft.AspNetCore.Cors 組件,所有問題就迎刃而解了。具體實現如下:

 

創建 wepapi項目

l  Dotnet new webapi

 

 

l  引入 cors組件

dotnet add package Microsoft.AspNetCore.Cors --version 2.0.1

 

 

 

 

l  服務端目錄結構

 

 

 

 

l  添加 cors服務

 

 
         
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

             //添加cors 服務
            services.AddCors(options => 
                                     options.AddPolicy("CorsSample",p => p.WithOrigins("http://localhost:5000")
            .AllowAnyMethod().AllowAnyHeader()));

            app.UseMvc();
        }
 
         

 

 

 

l  設定header original

 
         
public void ConfigureServices(IServiceCollection services)

        {

            services.AddMvc();

            //配置Cors
            app.UseCors("CorsSample");

        }
 
         

 

 

 

l  修改controller的 get 方法

namespace webApiDemo1.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
[EnableCors("CorsSample")]
public IEnumerable<string> Get() { return new string[] { DateTime.Now.ToString() }; } } }

 

l  編譯與運行 webapi

 

dotnet run

 

 

 

 

至此 服務端的所有工作都已完成,測試

 

 

 

 

客戶端

目錄結構

 

 

搭建webpack 下Vue + router +elementUI

如果不清楚如何搭建 vue+router+elementUI ,請自行度娘。

引入axios 組件

npm install axios

 

創建單頁組件UserInfo.vue

<template>

  <div class="userList">

       <el-button type="primary"  @click="handleClick">獲取服務端時間</el-button>

       <p>call from server:{{msg}}</p>

  </div>

</template>

 

 

<script>

  import axios from 'axios';

  export default{

    data(){

      return {

          msg:""

      }

    },

    methods: {

       handleClick(evt) {

        let _self=this;

        axios.get('http://localhost:5000/api/Values')

             .then(function (response) {

                 //debugger;

                 console.log(response);

                 _self.msg=response.data;

             })

            .catch(function (error) {

              console.log(error);

            });

       }

    }

  }

 

</script>

 

<style scoped>

.userList

{

   padding-top: 10px;

}

</style>

 

 

運行效果

npm run dev

 

 

 

 

注意:response的 original ,這可是cors的關鍵所在

 

 

本文vue+elementUI+router 參考了monster1935.github.io 代碼,再次感謝作者。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM