欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Access-Control-Allow-Origin - Ajax 请求跨越 CORS解决方案

程序员文章站 2022-07-10 10:27:27
...
$(document).ready(function() {
         $("#download").click(function() {
         $.ajax({
           url:'https://api.thingspeak.com/channels/899906/feeds.csv?start=2019-11-08%2019:10:08&end=2019-11-11%2019:11:11',
           crossDomain:true,
           type:'GET',
           data:{
             format:'csv',
           },
           success:function(response){
             window.location.href ='https://api.thingspeak.com/channels/899906/feeds.csv?start=2019-11-08%2019:10:08&end=2019-11-11%2019:11:11' ;
           },
           error:function() {
             $().text("There was an error processing your request.Please try again");
             }
         });
         });

       });

方案二:JSONP

 $.ajax({
        type: "GET",
        headers : {
          "Access-Control-Allow-Origin": "*",
          'Content-Type':'application/json'
        },
        crossDomain:true,
        url: 'https://localhost:44369/api/signList',
        dataType: 'jsonp',
        jsonpCallback: (data)=>{
          console.log(data)
        },
        jsonp: (data)=>{
          console.log(data)
        },
      })

// ajax with cross domain is true
 $.ajax({
        type: "GET",
        crossDomain: true,
        url: 'https://localhost:44369/api/signList',
        dataType: "json",
        success: data => {
            console.log(data)
        },
        error: (err) => {
          console.log('request json error' + err)
        }
      })

方案三,服务端设置 

header("Access-Control-Allow-Origin: *"); # 跨域处理

问题就解决了

1. .net Core (web api)为例子:

在startup.cs 文件中加入如下代码:

 services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
 

app.UseCors(options => options.AllowAnyOrigin());

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });

        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseCors(options => options.AllowAnyOrigin());
        }

运行结果如下:

Access-Control-Allow-Origin - Ajax 请求跨越 CORS解决方案

Access-Control-Allow-Origin - Ajax 请求跨越 CORS解决方案

参考文章:https://www.c-sharpcorner.com/article/enabling-cors-in-asp-net-core-api-application/

 

相关标签: 跨域请求问题