• netcore5下js请求跨域


    后端代码如下:

    using Microsoft.AspNetCore.Mvc;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
    
    namespace WebApplication.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
            // GET: api/<ValuesController>
            [HttpGet]
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    
            // GET api/<ValuesController>/5
            [HttpGet("{id}")]
            public string Get(int id)
            {
                return "value";
            }
    
            // POST api/<ValuesController>
            [HttpPost]
            public void Post([FromForm] string value)        //FromBody须改成FromFrom要不然跨域还是会报错
            {
            }
    
            // PUT api/<ValuesController>/5
            [HttpPut("{id}")]
            public void Put(int id, [FromBody] string value)
            {
            }
    
            // DELETE api/<ValuesController>/5
            [HttpDelete("{id}")]
            public void Delete(int id)
            {
            }
        }
    }
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.HttpsPolicy;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace WebApplication
    {
        public class Startup
        {
            readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddCors(options =>
                {
                    options.AddPolicy(name: MyAllowSpecificOrigins,
                                      builder =>
                                      {
                                          builder.WithMethods("get", "post").AllowAnyOrigin();//允许任何来源的主机访问
                                                
                                      });
                });
    
                services.AddControllersWithViews();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
                app.UseHttpsRedirection();
                app.UseStaticFiles();
    
                app.UseRouting();
               
    
                app.UseAuthorization();
                app.UseCors(MyAllowSpecificOrigins);
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }

    前端就是一个测试demo,代码如下:

    <HTML>
    <HEAD></HEAD>
    <script charset="utf-8">
    function createCORSRequest(method,url){
    var xhr = new XMLHttpRequest();
    if("withCredentials" in xhr){
    xhr.open(method,url,true);
    }else if(typeof XDomainRequest !="undifined"){
    xhr = new XDomainRequest();
    xhr.open(method,url);
    }else
    {
    xhr=null;
    }
    return xhr;
    }
    
    //get请求
    
    <!-- var request = createCORSRequest("get","https://localhost:44351/api/values"); -->
    <!-- if(request){ -->
    
    <!-- request.onload=function(){ -->
    <!-- alert(request.responseText); -->
    <!-- }; -->
    <!-- request.send(); -->
    <!-- } -->
    //post请求
    <!-- var request = createCORSRequest("post","https://localhost:44351/api/values"); -->
    <!-- if(request){ -->
    
     <!-- //request.withCredentials = "true";    //客户端设置跨域即可,前端不能设置,如果设置反而报错 -->
    <!-- //request.setRequestHeader('Access-Control-Allow-Origin','*'); -->
    <!-- //request.setRequestHeader('Content-Type','application/json'); -->
    <!-- //request.setRequestHeader('Origin','localhost:44351'); -->
    <!-- request.onload=function(){ -->
    <!-- alert(request.responseText); -->
    <!-- }; -->
    <!-- request.send("hello world!"); -->
    <!-- } -->
    </script>
    <BODY>
    
    <div id="i">
    test
    </div>
    </BODY>
    </HTML>
    Fork me on GitHub
  • 相关阅读:
    UVA 11198 Dancing Digits
    UVA 10085 The most distant state
    UVA 321 The New Villa
    UVA 10422 Knights in FEN
    poj2876
    poj2895
    poj2914
    poj2892
    poj2941
    LD SDK LDCControlDll 中 CXMLFile的进一步使用方法,建议以后改进
  • 原文地址:https://www.cnblogs.com/morec/p/14325240.html
Copyright © 2020-2023  润新知