vue-admin,asp.net core api結合開發的坑

  • 2020 年 8 月 14 日
  • 筆記

目前第一次基於vue-admin前端框架和core api 進行前後端開發,期間碰到了一些問題,希望各位以後不要再碰到!!

vue-admin的注意點

vue-admin前端框架基於axios封裝了一個request.js。這個js對於後端的定義了一個返回的code,20000是表示成功,而不是根據http的code200 進行請求成功的判斷!!沒看程式碼,不知道,一直報請求失敗!!

response => {
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      });
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again','Confirm logout',{
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload();
          });
        });
      }

跨域的問題

vue.config.js可以配置跨域,但是我一直沒有成功過。請求能夠到後台,但是參數一直沒有轉發過去。

       // 配置跨域
       '/api': {
         target: '//localhost:5008/api/',
         ws: true,
         changeOrigin: true,
         pathRewrite: {
           '^/api': ''
         }
       }
     }
  1. 第一次:如果配置的target是https的請求過不去。
    如果配置了vue的跨域並且target配置的是http,那麼aps.net core api必須配置綁定https的埠,中間件中有一個httpsredirect中間件請求才能正確的,參數才能完整的傳到後端!!

asp.net core api配置跨域

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();
        services.AddCors(options =>
        {
            options.AddPolicy(MyAllowSpecificOrigins, builder =>
            {
                builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
            });
        });
    }

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

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        //必須配置在routing和Authorization中間件之間
        app.UseCors(MyAllowSpecificOrigins);
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                //必須添加require cors
                pattern: "{controller=Home}/{action=Index}/{id?}").RequireCors(MyAllowSpecificOrigins);
        });
    }

配置好api的跨域以後,去掉vue的代理配置,在vue-admin的env配置文件中根據各個env添加對應的api的域名即可。

期間由於配置了vue的代理,導致請求的參數一直在後台獲取不到,懷疑了很久的axios的問題,百度上很多的文章都不靠譜,浪費了了很多時間!
一直懷疑是api的接收參數的方式有問題,axios的relayloader傳參,後台用httpbody接收,formdate用httpform接收。不要懷疑,懷疑可以用postman測試!
最終vue-admin框架的代理個人使用下來還是有問題的,如果是各位大佬知道怎麼用,不吝賜教!!