目的,运行本地api服务器,将本地设备数据推送到微信小程序或uniApp。正式环境遇到了跨域问题。以下是解决思路:
1.根据uniapp介绍:
**程序中使用uniCloud
各家小程序平台,均要求在小程序管理后台配置小程序应用的联网服务器域名,否则无法联网。
使用uniCloud后,开发者将不再需要自己购买、备案域名,直接将uniCloud的域名填写在小程序管理后台即可。(如需使用前端网页托管仍需进行域名备案)**
2.注册了uniCloud,看到了阿里云提供的“request域名”、“内置云存储上传域名”、“内置云存储下载域名”。并分别将其填写到了微信小程序的请求、上传、下载域名当中。
其中,阿里云的request域名为:https://api.next.bspapp.com/
在asp.net core mvc的program中进行了域名配置,运行网址https://api.next.bspapp.com/WeatherForecast 能返回success。但不能进入到WeatherForecast 方法!貌似https://api.next.bspapp.com返回了信息,但webapi服务器(提供WeatherForecast方法)并没有响应!!
//mvc中的配置
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//配置前端网址,可以写在配置文件中实现灵活配置
string[] urls = new[] { "https://api.next.bspapp.com" };
// 注册跨域服务到容器中
builder.Services.AddCors(options =>
options.AddDefaultPolicy(builder => builder.WithOrigins(urls)
.AllowAnyMethod().AllowAnyHeader().AllowCredentials()));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
//在uniapp的mainfest.json中配置
"devServer" : {
"proxy" : {
"/api" : {
"target" : "https://api.next.bspapp.com",
"changeOrigin" : true,
"ws" : true,
"secure" : false
}
}
},
"h5" : {
"template" : "index.html",
"title" : "自测项目",
"devServer" : {
"disableHostCheck" : false,
"proxy" : {
"/api" : {
"target" : "https://api.next.bspapp.com/", //请求的目标域名
"changeOrigin" : true,
"secure" : false,
"pathRewrite" : {
"^/api" : ""
}
}
},
"port" : 5091,
"https" : false
},
"router" : {
"mode" : "hash"
},
"domain" : "",
"optimization" : {
"treeShaking" : {
"enable" : true
}
}
}
//uniApp中发起请求
uni.request({
url: '/api/WeatherForecast', // 请求的url
method: 'GET',
success: (res) => {
uni.showToast({
title:"ok"
})
uni.showToast({
title:res.data[0].summary
})
},
fail: (err) => {
uni.showToast({
title:err.errMsg
})
}
})