­

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框架的代理个人使用下来还是有问题的,如果是各位大佬知道怎么用,不吝赐教!!