【发布时间】:2021-09-02 01:08:11
【问题描述】:
(我的英文不好) 您好,所以当我在我的服务器上有我的 Web API 然后尝试从我的主 PC 使用我的反应网站时,我遇到了问题,我得到 Cors 错误。当我在我的主电脑上同时运行我的 webAPI 和我的反应时,它会工作,但需要它从服务器上工作,因为我们有几个人在上面工作。
我希望有人可以帮助我。
错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ServerIP/api/user. (Reason: CORS request did not succeed).
我尝试了一些不同的方法,例如添加:
public static void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddDefaultPolicy(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
然后当这不起作用时,我尝试修复终点
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}"
);
endpoints.MapControllers();
});
还尝试在我们的两个控制器类前面添加这个
[EnableCors("*", "*", "*")]
这就是 React 的样子:
import Axios from 'axios'
const WorkifyAPI = Axios.create({
baseURL: 'https://ServerIP:42069/api'
})
export default WorkifyAPI
反应服务:
import http from '../WorkifyAPI'
const GetallWorkouts = (userID: string) => {
return http.get(`/user/${userID}/WorkoutData`)
}
export default {
GetallWorkouts,
}
编辑: starup.cs 目前的样子
public class Startup
{
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 static void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
}
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapControllers();
});
}
}
当我在 Chrome 中运行我的 React 时,我得到了这个错误: net::ERR_CERT_AUTHORITY_INVALID 正如@sideshowbarker 所说,这与 SSL 相关,所以会检查一下
【问题讨论】:
-
您使用的是哪个 dotnet 版本?
-
据我所见,代码是正确的。我有一个类似的问题,原来反向代理正在剥离 CORS 标头。也许你的情况也是这样?
-
“CORS 请求未成功”实际上表明问题与 CORS 无关。我的字面意思是浏览器未能成功完成请求。或者换句话说,这意味着事务从未到达服务器实际响应的点。它通常表示 SSL 失败。见developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/…。
-
我认为 sideshowbarker 和 Mekroebo 可能是正确的,并且该问题与前端应用程序或后端应用程序配置无关。您应该在 Web 开发人员工具中显示实际请求。
-
在
42069端口为https://ServerIP:42069调用https很可能是代理的指示。在这种情况下,配置 ssl 代理(和/或在这方面处理客户端设置)可能是前进的道路
标签: c# reactjs asp.net-web-api cors