第9章 前端调用POST-Api注意事项

news2024/9/24 19:17:01

1 “' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.”。异常

 1.1 通过跨域策略解决

1.1.1 在appsettings.json文件中定义跨域策略配置

  //  跨域(Cors)配置的域名及其端口集,该端口集中是否包含有vue/uni-app前端项目的访问域名及其端口,如果配置域名及其端口集中,不包含后端项目的访问域名及其端口,

  //且在“Program.cs” 文件进行了限定定义,那么vue/uni-app前端是不能与.Net(Core)后端项目进行交互操作的。

  //  跨域(Cors)策略配置的实质是:把物理上分的略前后端,在逻辑上统合到1个域名下(例如:http://localhost:8080),从而减可能少前端文章后端APIHTTP因跨域(Cors)操作而接生的异常,

  //所有当前程序中定义跨域(Cors)配置时,一般情况下就不用使用“CorsMiddleware”中间件了。

  "Cors": {

    "PolicyName": "CorsIpAccess", //vue/uni-app前端是不能与.Net(Core)后端项目进行交互操作的策略名称。

    "EnableAllIPs": false, //当为true时,开放所有IP均可访问。    

    //跨域(Cors)配置的域名及其端口集,用来限定vue/uni-app前端的访问及其交互操作。

    //注意:http://127.0.0.1:1818 http://localhost:1818 是不一样的

    "IPs": "http://localhost:8080,http://localhost:8081,http://localhost:8082,http://127.0.0.1:8080,http://127.0.0.1:8081,http://127.0.0.1:8082,https://localhost:443"

  },

1.1.2 重构 Program.cs

//通过AddCors依赖注入中间方法,把Cors(跨域)策略依赖中间件实例,注入到.Net(Core)框架默认容器中。

//Cors(跨域)操作是如果“appsettings.json”文件中配置的所有域名中,至少有1个与“vue/uni-app”前台项目相匹配域名时,则“vue/uni-app”前端项目就从当前后台项目中获取相关数据,从而实现页面的渲染显示。

builder.Services.AddCors(options =>

{

    //限定“appsettings.json”文件中配置的所有域名中,至少有1个与“vue/uni-app”前台项目相匹配域名,才能上“vue/uni-app”前端项目就从当前后台项目中获取相关数据,从而实现页面的渲染显示。

    if (!Convert.ToBoolean(builder.Configuration["Cors:EnableAllIPs"]))

    {

        options.AddPolicy(builder.Configuration["Cors:PolicyName"]!,

            policy =>

            {

                policy

                .WithOrigins(builder.Configuration["Cors:IPs"]!.Split(','))

                .AllowAnyHeader()

                .AllowAnyMethod();

            });

    }

    else

    {

        //不做限定,“vue”前台项目能够直接从当前后台项目中获取相关数据,从而实现页面的渲染显示

        options.AddPolicy(builder.Configuration["Cors:PolicyName"]!,

            policy =>

            {

                policy

                .SetIsOriginAllowed((host) => true)

                .AllowAnyMethod()

                .AllowAnyHeader()

                .AllowCredentials();

            });

    }

});

var app = builder.Build();

//把自定义管道中间中集成到.Net(Core)框架内置管道中,解决vue/uni-app前端项目(Cors)访问当前后端项目时,浏览器或App中出现的异常:

//    1“has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.”

//    2“has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.”

//    3“has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.”

//app.UseMiddleware<CorsMiddleware>();

//Cors(跨域)限制中间件管道中间中集成到.Net(Core)框架内置管道中,解决在由Hbuilder创建的前端Xuni-app项目(Cors)访问当前后端项目时,浏览器或App中会出现异常信息:

// “' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.”

//  跨域(Cors)策略配置的实质是:把物理上分离的前后端,在逻辑上统合到1个域名下(例如:http://localhost:8080),从而减可能少前端文章后端APIHTTP因跨域(Cors)操作而接生的异常,

//所有当前程序中定义跨域(Cors)配置时,一般情况下就不用使用“CorsMiddleware”中间件了。

app.UseCors(app.Configuration["Cors:PolicyName"]!);

//注意:在IIS部署时必须把下面两个管道中间件从“if (app.Environment.IsDevelopment())”取出,否则;“http://localhost:8090/Swagger/index.html”页面会出现“404”错误。

app.UseSwagger();

app.UseSwaggerUI();

1.2 或:通过WebApi.Middleware.CorsMiddleware解决

1.2.1 重构WebApi.Middleware.CorsMiddleware

using Microsoft.AspNetCore.Cors.Infrastructure;

namespace WebApi.Middleware

{

    /// <summary>

    /// 【跨域访问中间件--类】

    /// <remarks>

    /// 摘要:

    ///     该管道中间件类主要为了解决在由vue/uni-app前端项目(Cors)访问当前后端项目时,浏览器或App中出现的异常:

    ///    1“has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.”

    ///    2“has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.”

    ///    3“has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.”

    /// </remarks>

    /// </summary>

    public class CorsMiddleware

    {

        #region 拷贝构造方法与变量

        /// <summary>

        /// 【下1个】

        /// <remarks>

        /// 摘要:

        ///     .Net(Core)框架内置管道中的下1个管道中间件实例。

        /// </remarks>

        /// </summary>

        private readonly RequestDelegate _next;

        ///<param name="next">.Net(Core)框架内置管道中的下1个管道中间件实例。</param>

        /// <summary>

        /// 【拷贝构造方法】

        /// <remarks>

        /// 摘要:

        ///    通过该构造方法中的参数实例,实例化.Net(Core)框架内置管道中的下1个管道中间件实例。

        /// </remarks>

        /// </summary>

        public CorsMiddleware(RequestDelegate next)

        {

            _next = next;

        }

        #endregion

        #region 方法

        ///<param name="context">HTTP上下文实例。</param>

        /// <summary>

        /// 【异步调用】

        /// <remarks>

        /// 摘要:

        ///    通过该方法向.Net(Core)框架内置管道中集成当前管道中间件,解决由vue/uni-app前端项目(Cors)访问当前后端项目时,浏览器或App中出现的异常:

        ///    1“has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.”

        ///    2“has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.”

        ///    3“has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.”

        /// </remarks>

        /// </summary>

        public async Task InvokeAsync(HttpContext context)

        {

            //解决在由Hbuilder创建的前端Xuni-app项目(Cors)访问当前后端项目时,浏览器或App中会出现异常:

            //“has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.”

            if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Headers"))

            {

                context.Response.Headers.Add("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization");

            }

            if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Methods"))

            {

                context.Response.Headers.Add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,PATCH,OPTIONS");

            }

            //解决在由Hbuilder创建的前端Xuni-app项目(Cors)访问当前后端项目时,浏览器或App中会出现异常:

            //“has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.”

            if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))

            {

                context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

            }

            if (context.Request.Headers.ContainsKey(CorsConstants.Origin))

            {

                //解决在前端通过“axios.post”方式调用后端POST-API,如果前端“axios.post”方法没有加载“headers”参数实例,下1行语句中的配置,否则“axios.post”方法,访问后端的POST-API,否则会出现:"HTTP:415"错误。

                context.Request.ContentType = "application/json";

                //解决在由Hbuilder创建的前端Xuni-app项目(Cors)访问当前后端项目时,浏览器或App中会出现异常:

                //“' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.”

                if (context.Request.Method.Equals("OPTIONS"))

                {

                    context.Response.StatusCode = StatusCodes.Status200OK;

                    return;

                }

            }

            await _next(context);

        }

        #endregion

    }

}

1.2.2 重构 Program.cs

//通过AddCors依赖注入中间方法,把Cors(跨域)策略依赖中间件实例,注入到.Net(Core)框架默认容器中。

//Cors(跨域)操作是如果“appsettings.json”文件中配置的所有域名中,至少有1个与“vue/uni-app”前台项目相匹配域名时,则“vue/uni-app”前端项目就从当前后台项目中获取相关数据,从而实现页面的渲染显示。

//builder.Services.AddCors(options =>

//{

//    //限定“appsettings.json”文件中配置的所有域名中,至少有1个与“vue/uni-app”前台项目相匹配域名,才能上“vue/uni-app”前端项目就从当前后台项目中获取相关数据,从而实现页面的渲染显示。

//    if (!Convert.ToBoolean(builder.Configuration["Cors:EnableAllIPs"]))

//    {

//        options.AddPolicy(builder.Configuration["Cors:PolicyName"]!,

//            policy =>

//            {

//                policy

//                .WithOrigins(builder.Configuration["Cors:IPs"]!.Split(','))

//                .AllowAnyHeader()

//                .AllowAnyMethod();

//            });

//    }

//    else

//    {

//        //不做限定,“vue”前台项目能够直接从当前后台项目中获取相关数据,从而实现页面的渲染显示

//        options.AddPolicy(builder.Configuration["Cors:PolicyName"]!,

//            policy =>

//            {

//                policy

//                .SetIsOriginAllowed((host) => true)

//                .AllowAnyMethod()

//                .AllowAnyHeader()

//                .AllowCredentials();

//            });

//    }

//});

var app = builder.Build();

//把自定义管道中间中集成到.Net(Core)框架内置管道中,解决vue/uni-app前端项目(Cors)访问当前后端项目时,浏览器或App中出现的异常:

//    1“has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.”

//    2“has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.”

//    3“has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.”

app.UseMiddleware<CorsMiddleware>();

//Cors(跨域)限制中间件管道中间中集成到.Net(Core)框架内置管道中,解决在由Hbuilder创建的前端Xuni-app项目(Cors)访问当前后端项目时,浏览器或App中会出现异常信息:

// “' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.”

//  跨域(Cors)策略配置的实质是:把物理上分离的前后端,在逻辑上统合到1个域名下(例如:http://localhost:8080),从而减可能少前端文章后端APIHTTP因跨域(Cors)操作而接生的异常,

//所有当前程序中定义跨域(Cors)配置时,一般情况下就不用使用“CorsMiddleware”中间件了。

//app.UseCors(app.Configuration["Cors:PolicyName"]!);

//注意:在IIS部署时必须把下面两个管道中间件从“if (app.Environment.IsDevelopment())”取出,否则;“http://localhost:8090/Swagger/index.html”页面会出现“404”错误。

app.UseSwagger();

app.UseSwaggerUI();


2 在前端通过“axios.post”方式调用后端POST-API有,如果前端“axios.post”方法没有加载“headers”参数实例,下1行语句中的配置,否则“axios.post”方法,访问后端的POST-API,否则会出现:"HTTP:415"错误

2.1 前端解决方案

async PostAddRoleTestModel() {

                //"axios.post"方式直接加载“headers”参数实例,访问后端的POST-API,否则会出现:"HTTP:415"错误。

                let para1 = {

                    "name": "CCCCC",

                    "IsActive": false,

                    "Remark": "DDDDD"

                };

                let res1 = await axios.post('https://localhost:7043/Role/PostAddRoleTestModel', JSON.stringify(

                    para1), {

                    headers: {

                        "Content-Type": "application/json"

                    }

                });

                console.log("PostAddRoleTestModel-----res1-----", res1.data);

                //"axios.post"方式没有加载“headers”参数实例,需要在后端进行相应的配置,否则访问后端的POST-API,否则会出现:"HTTP:415"错误。

                let para2 = {

                    "name": "AAAAA",

                    "IsActive": true,

                    "Remark": "BBBBB"

                };

               

                console.log("PostAddRoleTestModel-----res2------");

                let res2 = await axios.post('https://localhost:7043/Role/PostAddRoleTestModel', JSON.stringify(

                    para2));

                console.log(res2.data);

            },

2.2 后端解决方案

    上述后端WebApi.Middleware.CorsMiddleware类所添加的:

                context.Request.ContentType = "application/json";

已经解决了这个问题。

        由于本人原因并没有通过跨域策略,来解决HTTP415错误,所以只好使用WebApi.Middleware.CorsMiddleware类,如果有跨域策略解决方案的朋友请在评论区给出解决方案。

3 WebApi.Controllers.RoleController

using Core;

using Core.Domain.Users;

using Core.Extensions;

using Data;

using Data.Extensions;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using Newtonsoft.Json;

using System.Linq.Expressions;

using WebApi.Models;

using WebApi.Test;

namespace WebApi.Controllers

{

    /// <summary>

    /// 【角色Api控制器--类】

    /// </summary>

    /// <remarks>

    /// 摘要:

    ///     通过该类中的方法成员,为前端角色页面提供Api方法和数据支撑。

    /// </remarks>

    [Route("[controller]/[action]")]

    [ApiController]

    public class RoleController : ControllerBase

    {

        #region 拷贝构造方法与变量

        private readonly EFCoreContext _context;

        public RoleController(EFCoreContext context)

        {

            _context = context;

        }

        #endregion

        #region 方法

        /// <summary>

        /// 【获取角色列表--需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     从角色表中获取角色实体的所有实例,并把这些实例存储到列表实例中。

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     列表实例,该实例存储着角色实体的所有实例。

        /// </returns>

        [HttpGet]

        public async Task<List<Role>> GetRoleListAsync()

        {

            return await _context.GetDbSet<Role>().ToListAsync();

        }

        [HttpGet]

        public async Task<MessageModel<PageModel<Role>>> GetRolePageByFromQueryAsync([FromQuery] PaginationModel pagination)

        {

            return null;

        }

        /// <summary>

        /// 【表单单击提交分页--需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     通过表单所传递的参数实例,获取符合条件的1指定页面内的所有数据,为指定页面的渲染显示提供数据支撑。

        /// 注意:

        ///     表单提交分页必须使用“[HttpPost]”进行标记。

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     消息模型纪录的1个指定实例,该实例存储当前“Api”方法的执行操作结果,为客户端页面的渲染提供数据支撑。

        /// </returns>

        [HttpPost]

        public async Task<MessageModel<PageModel<Role>>> PostRolePageByFromBodyAsync([FromBody] PaginationModel pagination)

        {

            //根据筛选字符串,为角色实例组合筛选lambda”表达式实例。

            Expression<Func<Role, bool>> _expression = null;

            if (!string.IsNullOrEmpty(pagination.QueryCondition))

            {

                _expression = ExpressionExtension.True<Role>();

                Role _role = JsonConvert.DeserializeAnonymousType(pagination.QueryCondition, new Role());

                if (_role!.Id > 0)

                {

                    _expression = _expression.And(p => p.Id == _role!.Id);

                }

                if (!string.IsNullOrEmpty(_role!.Name))

                {

                    _expression = _expression.And(p => p.Name.Contains(_role!.Name));

                }

                if (pagination.QueryCondition.Contains("IsActive", StringComparison.InvariantCultureIgnoreCase))

                {

                    _expression = _expression.And(p => p.IsActive == _role!.IsActive);

                }

                if (!string.IsNullOrEmpty(_role!.Remark))

                {

                    _expression = _expression.And(p => p.Remark.Contains(_role!.Remark));

                }

            }

            IQueryable<Role> _roleQueryable = _context.GetDbSet<Role>().AsQueryable();

            //获取所有符合条件的角色实例。

            if (_expression != null)

            {

                _roleQueryable = _roleQueryable.Where(_expression);

            }

            //把所有符合条件的角色实例,按照指定字段进行排序操作。

            if (!string.IsNullOrEmpty(pagination.OrderByFiled))

            {

                var _obj = JsonConvert.DeserializeAnonymousType(pagination.OrderByFiled, new

                {

                    Filed = "",

                    Type = "",

                });

                if (_obj!.Type.Equals("asc", StringComparison.InvariantCultureIgnoreCase))

                {

                    _roleQueryable = _roleQueryable.OrderBy(_obj!.Filed);

                }

                if (_obj!.Type.Equals("desc", StringComparison.InvariantCultureIgnoreCase))

                {

                    _roleQueryable = _roleQueryable.OrderByDescending(_obj!.Filed);

                }

            }

            else

            {

                _roleQueryable = _roleQueryable.OrderBy(r => r.Id);

            }

            //根据前端页面传递的参数,从角色表中获取(1逻辑页中的)相应行数的数据,并把这些数据存储到列表实例中。

            IPagedList<Role> _roleSinglePageList = await _roleQueryable.ToPagedListAsync((pagination.PageIndex - 1), pagination.PageSize);

            //实例化当前模型页(“物理页”),为当前页面的渲染显示提供数据支撑。

            PageModel<Role> _rolePageModel = new PageModel<Role>()

            {

                PageIndex = pagination.PageIndex,

                PageSize = pagination.PageSize,

                TotalCount = _roleQueryable.LongCount(),

                Data = _roleSinglePageList,

            };

            //实例化消息模型录,对当前“Api”控制器行方法的执行操作结果进行存储,为客户端页面的渲染提供数据支撑。

            MessageModel<PageModel<Role>> _roleMessageModel = new MessageModel<PageModel<Role>>()

            {

                Success = true,

                Message = "获取成功",

                Response = _rolePageModel,

            };

            return _roleMessageModel;

        }

        /// <param name="id">角色实体1个指定实例的长整型编号值。</param>

        /// <summary>

        /// 【获取1个角色--需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     从角色表获取角色实体的1个指定实例。

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     角色实体的1个指定实例。

        /// </returns>

        [HttpGet]

        public async Task<Role> GetRoleSingleAsync([FromQuery] long id)

        {

            Role _model = await _context.GetDbSet<Role>().SingleAsync(role => role.Id == id);

            return _model;

        }

        /// <param name="role">角色实体的1个指定实例。</param>

        /// <summary>

        /// 【添加角色--需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     把角色实体1个指定实例持久化到持久化到角色表中。

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     角色实体的1个指定实例。

        /// </returns>

        [HttpPost]

        public async Task<Role> PostAddRoleAsync([FromBody] Role role)

        {

            await _context.GetDbSet<Role>().AddAsync(role);

            await _context.SaveChangesAsync();

            return role;

        }

        /// <param name="roleTestModel">角色测试模型的1个指定实例。</param>

        /// <summary>

        /// 【更新角色--需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     通过1个指定的长整型编号值,对1个角色实体1个指定实例并持久化到角色表的指定行中。

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     角色实体的1个指定实例。

        /// </returns>

        [HttpPut]

        public async Task<Role> PutUpdateRoleAsync([FromBody] RoleTestModel roleTestModel)

        {

            Role _model = await _context.GetDbSet<Role>().SingleAsync(role => role.Id == roleTestModel.Id);

            _model.Name= roleTestModel.Name;

            _model.IsActive= roleTestModel.IsActive;

            _model.Remark= roleTestModel.Remark;

            _context.GetDbSet<Role>().Update(_model);

            await _context.SaveChangesAsync();

            return _model;

        }

        /// <param name="id">角色实体1个指定实例的长整型编号值。</param>

        /// <summary>

        /// 【删除1个角色--需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     从角色表中删除1行指定的数据

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     消息模型纪录的1个指定实例,该实例存储当前“Api”方法的执行操作结果,为客户端页面的渲染提供数据支撑。

        /// </returns>

        [HttpDelete]

        public async Task<MessageModel<string>> DeleteRoleSingleAsync(long id)

        {

            Role _model = await _context.GetDbSet<Role>().SingleAsync(role => role.Id == id);

            if (_model == null)

            {

                return new MessageModel<string>()

                {

                    Success = false,

                    Status = 500,

                    Message = "不存需要被删除的数据!!",

                    Response = null,

                };

            }

             _context.GetDbSet<Role>().Remove(_model!);

            int count = await _context.SaveChangesAsync();

            return new MessageModel<string>()

            {

                Success = true,

                Status = 200,

                Message = "删除成功!",

                Response = null,

            };

        }

        /// <param name="idArray">角色实体多个指定实例的长整型编号值的字符串集,值之间用进行分割。</param>

        /// <summary>

        /// 【删除多个角色--需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     从角色表中删除多行指定的数据

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     消息模型纪录的1个指定实例,该实例存储当前“Api”方法的执行操作结果,为客户端页面的渲染提供数据支撑。

        /// </returns>

        [HttpDelete]

        public async Task<MessageModel<string>> DeleteRoleArrayAsync(string idArray)

        {

            string[] _idArray = idArray.Split(",").ToArray();

            List<Role> _roleList = new List<Role>();

            foreach (string id in _idArray)

            {

                long _id = Convert.ToInt64(id);

                Role _model = await _context.GetDbSet<Role>().SingleAsync(role => role.Id == _id);

                if (_model != null)

                    _roleList.Add(_model);

            }

            if (_roleList == null|| _roleList.Count<=0)

            {

                return new MessageModel<string>()

                {

                    Success = false,

                    Status = 500,

                    Message = "不存需要被删除的数据!!",

                    Response = null,

                };

            }

            _context.GetDbSet<Role>().RemoveRange(_roleList);

            int count = await _context.SaveChangesAsync();

            return new MessageModel<string>()

            {

                Success = true,

                Status = 200,

                Message = "删除成功!",

                Response = null,

            };

        }

        #endregion

        #region 方法--测试

        /// <param name="roleTestModel">角色测试模型的1个指定实例。</param>

        /// <summary>

        /// 【添加角色(测试模型)--需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     把角色实体1个指定实例持久化到持久化到角色表中(只是测试使用,可以被删除)

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     角色实体的1个指定实例。

        /// </returns>

        [HttpPost]

        public async Task<Role> PostAddRoleTestModelAsync([FromBody] RoleTestModel roleTestModel)

        {

            Role role = new Role() { Name = roleTestModel.Name, IsActive = roleTestModel.IsActive, Remark = roleTestModel.Remark };

            await _context.GetDbSet<Role>().AddAsync(role);

            await _context.SaveChangesAsync();

            return role;

        }

        #endregion

    }

}

4 前端调用

<script>

    import axios from 'axios'

    export default ({

        data() {

            return {

                roleAllList: [],

            };

        },

        methods: {

            //获取角色实体的所有实例。

            async getRoleList() {

                let res = await axios.get('https://localhost:7043/Role/GetRoleList');

                //console.log(res.data);

                this.roleAllList = res.data;

            },

            //“GET”方式获取角色实体的1个指定实例。

            async GetRoleSingle() {

                let para = {

                    id: 10,

                };

                let res = await axios.get('https://localhost:7043/Role/GetRoleSingle', {

                    params: para

                });

                console.log("GetRoleSingle-----", res.data);

            },

            async PostAddRoleTestModel() {

                //"axios.post"方式直接加载“headers”参数实例,访问后端的POST-API,否则会出现:"HTTP:415"错误。

                let para1 = {

                    "name": "CCCCC",

                    "IsActive": false,

                    "Remark": "DDDDD"

                };

                let res1 = await axios.post('https://localhost:7043/Role/PostAddRoleTestModel', JSON.stringify(

                    para1), {

                    headers: {

                        "Content-Type": "application/json"

                    }

                });

                console.log("PostAddRoleTestModel-----res1-----", res1.data);

                //"axios.post"方式没有加载“headers”参数实例,需要在后端进行相应的配置,否则访问后端的POST-API,否则会出现:"HTTP:415"错误。

                let para2 = {

                    "name": "AAAAA",

                    "IsActive": true,

                    "Remark": "BBBBB"

                };

                console.log("PostAddRoleTestModel-----res2------");

                let res2 = await axios.post('https://localhost:7043/Role/PostAddRoleTestModel', JSON.stringify(

                    para2));

                console.log(res2.data);

            },

            async PutUpdateRole() {

                //"axios.post"方式直接加载“headers”参数实例,访问后端的POST-API,否则会出现:"HTTP:415"错误。

                let para1 = {

                    "Id": 10,

                    "name": "CCCCCUpdate",

                    "IsActive": false,

                    "Remark": "DDDDDUpdate"

                };

                let res1 = await axios.put('https://localhost:7043/Role/PutUpdateRole', JSON.stringify(

                    para1), {

                    headers: {

                        "Content-Type": "application/json"

                    }

                });

                console.log("PutUpdateRole-----res1-----", res1.data);

                //"axios.post"方式没有加载“headers”参数实例,需要在后端进行相应的配置,否则访问后端的POST-API,否则会出现:"HTTP:415"错误。

                let para2 = {

                    "Id": 10,

                    "name": "AAAAAUpdate",

                    "IsActive": true,

                    "Remark": "BBBBBUpdate"

                };

                console.log("PutUpdateRole-----res2------");

                let res2 = await axios.put('https://localhost:7043/Role/PutUpdateRole', JSON.stringify(

                    para2));

                console.log(res2.data);

            },

           

            async DeleteRoleSingle() {

                let para = {

                    "Id": 608

                };

                let res = await axios.delete('https://localhost:7043/Role/DeleteRoleSingle',  {

                    params: para

                });

                console.log("DeleteRoleSingle-----res-----", res.data);

            },

           

            async DeleteRoleArray() {

                let para = {

                    "idArray": "545,546,547"

                };

                let res = await axios.delete('https://localhost:7043/Role/DeleteRoleArray',  {

                    params: para

                });

                console.log("DeleteRoleArray-----res-----", res.data);

            },

           

            async PostRolePageByFromBody() {

                //"axios.post"方式直接加载“headers”参数实例,访问后端的POST-API,否则会出现:"HTTP:415"错误。

                let para = {

                    PageIndex: 2,

                    PageSize: 5,

                    OrderByFiled: "{\"Filed\":\"id\",\"Type\":\"desc\"}",

                    QueryCondition: "{\"Name\":\"\",\"IsActive\":true}"

                };

                let res1 = await axios.post('https://localhost:7043/Role/PostRolePageByFromBody', JSON.stringify(

                    para), {

                    headers: {

                        "Content-Type": "application/json"

                    }

                });

                console.log("PostRolePageByFromBody-----res1-----", res1.data);

                console.log("PostRolePageByFromBody-----res2------");

                //"axios.post"方式没有加载“headers”参数实例,需要在后端进行相应的配置,否则访问后端的POST-API,否则会出现:"HTTP:415"错误。

                let res2 = await axios.post('https://localhost:7043/Role/PostRolePageByFromBody', JSON.stringify(

                    para));

                console.log(res2.data);

            },

            async GetRolePageByFromQuery() {

                //"axios.get"方式需要直接加载“headers”参数实例,访问后端的GET-API,也不会出现:"HTTP:415"错误,同理也不必在端进行相应的配置。

                let para = {

                    PageIndex: 2,

                    PageSize: 5,

                    OrderByFiled: "{\"Filed\":\"id\",\"Type\":\"desc\"}",

                    QueryCondition: "{\"Name\":\"\",\"IsActive\":true}"

                };

                let res1 = await axios.get('https://localhost:7043/Role/GetRolePageByFromQuery', {

                    params: para

                });

                console.log("GetRolePageByFromQuery-----res1-----", res1.data);

            },

        },

        mounted() {

            //this.getRoleList();

            //this.GetRoleSingle();

            //this.PostAddRoleTestModel();

            //this.PutUpdateRole();

            //this.DeleteRoleSingle();

            //this.DeleteRoleArray();

            this.PostRolePageByFromBody();

            //this.GetRolePageByFromQuery();

        }

    });

</script>

对以上功能更为具体实现和注释见:

1、221230_006ShopDemo(前端调用POST-Api注意事项)

2、221230_004shopvue(前端调用POST-Api注意事项)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/130305.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

央视春晚彩排的关键时刻,主持人朱军终于回归了

盼望着、盼望着&#xff0c;春节临近了&#xff0c;春晚的零点钟声即将开始敲响了。一年一度的央视春晚&#xff0c;已经开启了第一次彩排&#xff0c;众多明星都参与其中&#xff0c;看来今年的春晚要热闹了。 虽然只是第一次彩排&#xff0c;但是很多明星艺人都已经亮相&…

Colyseus:轻量级多人游戏免费开源解决方案

点击上方“青年码农”关注回复“源码”可获取各种资料Colyseus 是一个独特的多人游戏框架&#xff0c;被用于许多 H5 小游戏和手机游戏中&#xff0c;使用容易&#xff0c;且选项众多&#xff0c;可满足开发者多样化的需求。如果你在制作多人联网游戏时遇到过各种扩展性需求和细…

数据卷(Data Volumes)

目录 1.Docker宿主机和容器之间文件拷贝 利用MySQL镜像安装MySQL服务 从容器中拷贝文件到宿主机 从宿主机拷贝文件到容器 2.数据卷 3.数据卷容器 1.Docker宿主机和容器之间文件拷贝 利用MySQL镜像安装MySQL服务 docker run -p 3307:3306 --name mysql2 -di -v /home/…

Qt中用thrift验证flume

一.flume简介 flume是Cloudera提供的一个高可用的&#xff0c;高可靠的&#xff0c;分布式的海量日志采集、聚合和传输的系统。 在flume中分为了3个组件&#xff0c;分别为source&#xff0c;channel和sink。 Source是负责接收数据到Flume Agent的组件。Source组件可以处理各种…

在阿里做了7年软件测试原来是........

你了解软件测试岗吗&#xff1f; 很多人做测试3&#xff0c;5年&#xff0c;甚至年限多长。 但并不懂软件测试岗所要求的技术和能力&#xff0c;只是拘于当前的工作环境和培训班的宣传。 在一个微信里中看到如下的对话&#xff1a; 某人说&#xff0c;工作中开始做自动化了。…

8253练习题(8253端口地址怎么求?怎么求初值?怎么看出工作方式)

目录 一&#xff1a;简单&#xff08;题目把计数初值和工作方式都给你了&#xff09; 二&#xff1a;给了你输入时间周期和初值&#xff0c;你会不会求输出&#xff1f; 三&#xff1a;简单 四&#xff1a;初值计数方式都不给&#xff0c;初值还是给的时间和频率混合 五&a…

前端_swapCache方法 发布文章

swapCache方法 swapCache方法用来手工执行本地缓存的更新&#xff0c;它只能在applicationCache对象的updateReady事件被触发时调用&#xff0c;updateReady事件只有服务器上的manifest文件被更新&#xff0c;并且把manifest文件中所要求的资源文件下载到本地后触发。顾名思义…

[极客大挑战 2019]Secret File(BUUCTF)

前言: 这篇文章还是是为了帮助一些 像我这样的菜鸟 找到简单的题解 题目描述 解题工具: fiddler或burpsuite抓包 解题过程: 又是要找秘密&#xff0c; 先检查一下源代码 发现了一个链接与背景颜色融合了 点进去看看 找到了SECRET但肯定没这么简单 点击SECRET页面发生…

15. 我是怎么用一个特殊 Cookie ,限制住别人的爬虫的

爬虫训练场&#xff0c;第15篇博客。 博客详细清单&#xff0c;参考 https://pachong.vip/blog 本次案例&#xff0c;用定值 Cookie 实现反爬 文章目录Cookie 生成Python Flask 框架生成 CookieFlask make_response 加载模板Flask 判断指定 cookie 是否存在补充知识点Cookie 生…

【AcWing每日一题】4818. 奶牛大学

Farmer John 计划为奶牛们新开办一所大学&#xff01; 有 N 头奶牛可能会入学。 每头奶牛最多愿意支付 ci 的学费。 Farmer John 可以设定所有奶牛入学需要支付的学费。 如果这笔学费大于一头奶牛愿意支付的最高金额&#xff0c;那么这头奶牛就不会入学。 Farmer John 想赚…

C++ New和Delete

目录 前言 New Delete 前言 new是c中用于动态申请空间的运算符&#xff0c;malloc也是用于动态申请空间的&#xff0c;但malloc是函数。 New new是用来开辟一段新空间的&#xff0c;和一般申明不同的是&#xff0c;new开辟的新空间是在堆上&#xff0c;而申明的变量是在栈上…

【自学Java】Java注释

Java注释 Java注释教程 用于注解说明解释程序的文字就是注释&#xff0c;注释可以提高代码的阅读性。同时&#xff0c;注释也是一个程序员必须要具有的良好的编程习惯。我们首先应该将自己的思想通过注释先整理出来&#xff0c;再用代码实现。 在 Java 语言 中&#xff0c;一…

(二)Qt多线程实现海康工业相机图像实时采集

系列文章目录 提示&#xff1a;这里是该系列文章的所有文章的目录 第一章&#xff1a; &#xff08;一&#xff09;QtOpenCV调用海康工业相机SDK示例开发 第二章&#xff1a; &#xff08;二&#xff09;Qt多线程实现海康工业相机图像实时采集 文章目录系列文章目录前言一、项目…

C语言中指针常见问题集

1. 我想声明一个指针并为它分配一些空间,但却不行。这些代码有什么问题&#xff1f; char *p; *p malloc(10);答&#xff1a;你所声明的指针是p, 而不是*p, 当你操作指针本身时你只需要使用指针的名字即可:cp malloc(10);当你操作指针指向的内存时,你才需要使用*作为间接操…

坚果的2022年终总结

人生天地之间&#xff0c;若白驹过隙&#xff0c;转眼间&#xff0c;这一年又快要过去了&#xff0c;按照惯例还是写一篇年终总结&#xff0c;同时也看一下自己是否又成长&#xff0c;是否有哪些事情没做好&#xff0c;给自己做一个复盘。一、缘起OpenHarmony我是从去年开始参加…

Webpack 钩子介绍、手写 Webpack Plugin

目录 1. Plugin 用作和工作原理 1.1 Plugin 的作用 1.2 Plugin 的工作原理 2. Webpack 底层逻辑和钩子介绍 2.1 Webpack 内部执行流程 2.2 Webpack 内部钩子 2.2.1 钩子是什么 2.2.2 Tapable —— 为 Webpack 提供 Plugin 钩子 数据类型接口 定义 2.2.3 Compiler Hook…

C#,图像二值化(08)——灰度图像二值化,全局算法,全局阈值优化算法及其源代码

1、全局阈值算法 基于灰度直方图的优化迭代算法之一。 Iterative Scheduler and Modified Iterative Water-Filling In the downlink, the inter-cell interference is only function of the power levels and is independent of the user scheduling decisions. This suggest…

俺的2022年

年末将至&#xff0c;还是要写点总结性的内容&#xff0c;以回顾过去一年做的各种事情。工作之外从客观数据上看&#xff0c;今年的收入水平略差于去年&#xff0c;主要是工作外的收入有所减少&#xff0c;其核心原因是没有录制新的课程内容进行变现&#xff0c;原本的计划是&a…

【自学Python】Python介绍

Python教程 什么是编程语言 编程语言&#xff08;programming language&#xff09;&#xff0c;是用来定义计算机程序的形式语言。它是一种被标准化的交流技巧&#xff0c;用来向计算机发出指令。 也可以说&#xff0c;计算机语言让程序员能够准确地定义计算机所需要使用的…

拓展交流空间,分享开发精彩 | 开发者说·DTalk 鉴赏

日月其迈&#xff0c;岁律更新&#xff0c;时间的洗礼让开发者们更加坚韧&#xff0c;持续探索&#xff0c;不断追求&#xff0c;同样也激励着我们为开发者提供更多的帮助与支持。不断迭代的技术产品是开发者们的趁手工具&#xff0c;定期更新的政策助力打造安全可靠的生态&…