zoukankan      html  css  js  c++  java
  • asp.net core 2.0 api ajax跨域问题

    API配置:
    services.AddCors(options => { options.AddPolicy("any", builder => { builder.WithOrigins("http://localhost") //指定允许来源的主机访问 .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials();//指定处理cookie }); }); //设置全局筛选器,全局控制器启用core services.Configure<MvcOptions>(options => options.Filters.Add(new CorsAuthorizationFilterFactory("any")));

    客户端:

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
        <meta charset="utf-8" />
        <script src="jquery.min.js"></script>
    </head>
    <body>
        <input id="login" value="登录" type="button" />
        <input id="sava" value="保存" type="button" />
        <span id="message"></span>
        <script>
     
            $("#sava").click(function () {
                $.ajax({
                    type: 'GET',
                    url: "http://localhost:54821/api/v1/garbage/type",
                    data: {  },
                    dataType: "json",
                    //必须有这项的配置,不然cookie无法发送至服务端
                    xhrFields: {
                        withCredentials: true
                    },
                    success: function (result) {
                    alert(result.code);
                        $("#message").html(result);
                    },
                    error: function (xhr,status) {
                    alert("失败");
                        $("#message").html(status);
                    }
                });
            })
        </script>
    </body>
    </html>

    此时设置全局启用,控制器中可以使用

  • 相关阅读:
    Vue项目端口号占用
    理解vuex -- vue的状态管理模式
    2018-7-10杂记
    JS 数组操作总结
    JS 字符串操作总结
    【javascript练习题】函数
    【javascript练习题】this指针和作用域
    canal实时同步mysql binlog到rabbitmq
    Hexo+GitHub+Netlify一站式搭建属于自己的博客网站
    Git学习原版手稿
  • 原文地址:https://www.cnblogs.com/mebius4789/p/8535646.html
Copyright © 2011-2022 走看看