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>
netcore5下js请求跨域的更多相关文章
- 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:/ ...
- JS JSOP跨域请求实例详解
JSONP(JSON with Padding)是JSON的一种“使用模式”,可用于解决主流浏览器的跨域数据访问的问题.这篇文章主要介绍了JS JSOP跨域请求实例详解的相关资料,需要的朋友可以参考下 ...
- js执行跨域请求
//js执行跨域请求 var _script = document.createElement('script'); _script.type = "text/javascript" ...
- easy ui Tree请求跨域数据
扯淡篇: jQuery EasyUI为提供了大多数UI控件的使用,如:accordion,combobox,menu,dialog,tabs,validatebox,datagrid,window,t ...
- day78_淘淘商城项目_11_单点登录系统实现 + 用户名回显 + ajax请求跨域问题详解_匠心笔记
课程计划 1.SSO注册功能实现 2.SSO登录功能实现 3.通过token获得用户信息 4.ajax跨域请求解决方案--jsonp 1.服务接口实现 SSO系统就是解决分布式环境下登录问题的,本 ...
- 百万年薪python之路 -- 请求跨域和CORS协议详解
楔子 什么是同源策略 同源策略,它是由Netscape提出的一个著名的安全策略.现在所有支持JavaScript 的浏览器都会使用这个策略.所谓同源是指,域名,协议,端口相同.当一个浏览器的两个tab ...
- 关于vue-cli3中配置请求跨域的问题
关于vue-cli3中配置请求跨域的问题 根据Vue CLI3官方文档, 需要在vue.config.js文件中配置devServer.proxy选项来解决跨域问题. 关于vue.config.js文 ...
- http请求跨域问题分析
http请求跨域问题分析 个人认为可能涉及很多http的知识,本人才疏学浅不敢妄自揣测,只是做个笔记为了以后对比理解,从原生fetch说起吧,前提假设有个后端服务,我用express来模拟,如下: v ...
- js调用跨域
web aapi 初体验 解决js调用跨域问题 跨域界定 常见跨域: 同IP不同端口: http:IP:8001/api/user http:IP:8002/api/user 不同IP不同 ...
- Vue(项目踩坑)_解决vue中axios请求跨域的问题
一.前言 今天在做项目的时候发现axios不能请求跨域接口 二.主要内容 1.之前直接用get方式请求聚合数据里的接口报错如下 2.当前请求的代码 3.解决方法 (1)在项目目录中依次找到:confi ...
随机推荐
- 记录--JS-SDK页面打开提示realAuthUrl错误
这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助 测试环境好好地功能,上了生产,莫名其妙报错,开始以为是没有设置Js安全接口域名,结果让相应人员一查,已经设置了相应的域名,再看下公众号内的 ...
- Java中一个逐渐被遗忘的强大功能,强到你难以置信!!
大家好,我是冰河~~ 说起Java,简单好用,但是Java中很多牛逼的技术却逐渐被遗忘了~~ 在Java语言出现之前,很多系统都是使用C和C++开发的.Java出现之后,由于其面向对象的思想更加符合人 ...
- SpringBoot项目 前后端分离 ajax附件上传下载
前台界面 上传 下载 前台代码 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "ht ...
- nginx location块
location块在server块中使用,它的作用是根据客户端请求URL去定位不同的应用. 匹配格式 作用 location = /uri = 表示精确匹配,只有完全匹配上才能生效 location ...
- C# OpenCv 证件照换底色
using OpenCvSharp; using System; using System.Collections.Generic; using System.Linq; using System.T ...
- Web、Android等程序开发中src引入外部文件和资源的方法总结
方法一:使用相对于当前文件(源文件)的相对路径 使用 ../ 对于这个例子来说 ../ 把路径带到了项目根目录的下一级目录 1 <script src="../static/js/wo ...
- #KMP,容斥,dp#洛谷 5770 [JSOI2016] 无界单词
题目传送门 分析 显然如果存在长度大于一半的border那么必然存在小于一半的 border,所以容斥一下, 设 \(dp[i]\) 表示长度为 \(i\) 的不存在公共前后缀的字符串个数,那么 \( ...
- #线段树,二分#洛谷 2824 [HEOI2016/TJOI2016]排序
题目 分析 这排序就很难实现,考虑定一个基准,小于该基准的视为0,否则视为1, 那排序可以看作将0和1分开,这就很好用线段树实现了 如果该位置是0,说明这个基准太高,显然可以用二分答案(基准),那么时 ...
- Git 版本控制系统的完整指南
什么是 Git? Git 是一个流行的版本控制系统.它是由 Linus Torvalds 于 2005 年创建的,自那时以来由 Junio Hamano 维护. 它用于: 跟踪代码更改 跟踪谁做出了更 ...
- 鸿蒙HarmonyOS实战-ArkUI组件(CustomDialog)
一.CustomDialog CustomDialog组件是一种自定义对话框,可以通过开发人员根据特定的要求定制内容和布局.它允许开发人员创建一个完全可定制的对话框,可以显示任何类型的内容,例如文本. ...