跨域问题只存在于基于浏览器的 Web 开发中。由于小程序的宿主环境不是浏览器,而是微信客户端,所以小程序中不存在跨域的问题。
Ajax 技术的核心是依赖于浏览器中的 XMLHttpRequest 这个对象,由于小程序的宿主环境是微信客户端,所以小程序中不能叫做“发起Ajax 请求”,而是叫做“发起网络数据请求”。
新建http://localhost:5175的iis网站,放入index.html,当做web服务器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>跨域请求测试</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
$(function () {
$.ajax({
type: "GET",
url: "http://localhost:5156/home",
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (err) {
console.error(err)
}
})
})
</script>
</html>
新建asp.net core web项目,监听端口为5156
Program.cs
namespace AspnetcoreCorsStu01
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseRouting();
app.MapControllers();
app.Run();
}
}
}
新建HomeController
using Microsoft.AspNetCore.Mvc;
namespace AspnetcoreCorsStu01
{
[ApiController]
[Route("[controller]")]
public class HomeController
{
/// <summary>
/// index方法
/// </summary>
/// <returns></returns>
[HttpGet]
public string Index()
{
return "Hello World";
}
}
}
请求结果
修改代码允许跨域
namespace AspnetcoreCorsStu01
{
public class Program
{
public static void Main(string[] args)
{
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
policy =>
{
//允许请求的域名,可以传入多个
policy
.WithOrigins("http://localhost:5175")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddControllers();
var app = builder.Build();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.MapControllers();
app.Run();
}
}
}
cors
中间件顺序
https://blog.csdn.net/qq_61950936/article/details/127167950