后端代码如下:

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>

netcore5下js请求跨域的更多相关文章

  1. js&jquery跨域详解jsonp,jquery并发大量请求丢失回调bug

    URL  说明 是否允许通信 http://www.a.com/a.js http://www.a.com/b.js 同一域名下 允许 http://www.a.com/lab/a.js http:/ ...

  2. JS JSOP跨域请求实例详解

    JSONP(JSON with Padding)是JSON的一种“使用模式”,可用于解决主流浏览器的跨域数据访问的问题.这篇文章主要介绍了JS JSOP跨域请求实例详解的相关资料,需要的朋友可以参考下 ...

  3. js执行跨域请求

    //js执行跨域请求 var _script = document.createElement('script'); _script.type = "text/javascript" ...

  4. easy ui Tree请求跨域数据

    扯淡篇: jQuery EasyUI为提供了大多数UI控件的使用,如:accordion,combobox,menu,dialog,tabs,validatebox,datagrid,window,t ...

  5. day78_淘淘商城项目_11_单点登录系统实现 + 用户名回显 + ajax请求跨域问题详解_匠心笔记

    课程计划 1.SSO注册功能实现 2.SSO登录功能实现 3.通过token获得用户信息 4.ajax跨域请求解决方案--jsonp 1.服务接口实现   SSO系统就是解决分布式环境下登录问题的,本 ...

  6. 百万年薪python之路 -- 请求跨域和CORS协议详解

    楔子 什么是同源策略 同源策略,它是由Netscape提出的一个著名的安全策略.现在所有支持JavaScript 的浏览器都会使用这个策略.所谓同源是指,域名,协议,端口相同.当一个浏览器的两个tab ...

  7. 关于vue-cli3中配置请求跨域的问题

    关于vue-cli3中配置请求跨域的问题 根据Vue CLI3官方文档, 需要在vue.config.js文件中配置devServer.proxy选项来解决跨域问题. 关于vue.config.js文 ...

  8. http请求跨域问题分析

    http请求跨域问题分析 个人认为可能涉及很多http的知识,本人才疏学浅不敢妄自揣测,只是做个笔记为了以后对比理解,从原生fetch说起吧,前提假设有个后端服务,我用express来模拟,如下: v ...

  9. js调用跨域

    web aapi 初体验 解决js调用跨域问题   跨域界定 常见跨域: 同IP不同端口: http:IP:8001/api/user     http:IP:8002/api/user 不同IP不同 ...

  10. Vue(项目踩坑)_解决vue中axios请求跨域的问题

    一.前言 今天在做项目的时候发现axios不能请求跨域接口 二.主要内容 1.之前直接用get方式请求聚合数据里的接口报错如下 2.当前请求的代码 3.解决方法 (1)在项目目录中依次找到:confi ...

随机推荐

  1. Dll堆栈问题(Dll的静态变量与全局变量、vs的MT与MD)

    问题引入:dll有一个导出函数,函数参数是string&,string在函数内部被=赋值.在exe动态加载此dll,调用此导出函数后,会崩溃. 原因:如果任何STL类的实现中使用了静态变量(我 ...

  2. .Net MinimalApis响应返回值

    前言 文本主要讲 MinimalApis 中的使用自定义IResultModel和系统自带IResult做响应返回值. MinimalApis支持以下类型的返回值: string - 这包括 Task ...

  3. 把分钟数转化成几小时几分钟(100 -> 01:40)

    /// <summary> /// 把分钟数转化成几小时几分钟(100 -> 01:40) /// </summary> /// <param name=" ...

  4. 技嘉主板开启VT

    AM4接口主板开启虚拟化: M.I.T.->Advanced Frequency Settings->Advanced CPU Core Settings->SVM Mode (虚拟 ...

  5. 使用MFT进行加密文件传输的7个好处

    至少,托管文件传输(MFT)解决方案是一种产品,它包含入站和出站文件传输的所有方面,同时使用行业标准的网络协议和无缝加密.它可以从单个集中管理点在您的网络,系统,应用程序,贸易伙伴和云环境中自动化和传 ...

  6. 使用EasyPoi导出excel时如何避免导出null

    使用replace将null替换为空字符串 @Excel(name = "是否自动开始", replace = { "是_1", "否_0" ...

  7. KingbaseES例程_普通表在线转分区表(基于规则)

    KingbaseES例程_普通表在线转分区表 概述 普通表转分区表,使用视图的替换式规则,以路由方式,实现在线转移数据. 数据准备 /*普通大表*/ create table tab_single a ...

  8. C++ 中的可移植性和跨平台开发

    在当今软件开发行业中,跨平台开发已经成为了一种非常流行的方式.C++作为一门强大的编程语言,也被广泛应用于跨平台开发中.然而,由于不同操作系统的差异和限制,C++在不同的平台上的表现可能会有所不同.为 ...

  9. 2019.2版本的idea没有忽略提交图标-configure ignored files

    在SVN面板中  没有-configure ignored files 解决 1.打开 Settings→Editor→File Types2.在下方 Ignore files and folders ...

  10. Python 爬虫初探

    准备部分 0x01 爬虫的简介和价值 a. 简介 自动抓取互联网数据的程序,是基础技术之一 b. 价值 快速提取网络中有价值的信息 0x02 爬虫的开发环境 a. 环境清单 Python3.7 开发环 ...