azure 请求的资源上不存在“Access-Control-Allow-Origin”标头

j91ykkif  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(159)

获取此错误:

Access to fetch at 'https://myurl.azurewebsites.net/Player/1' from origin 'http://localhost:19006' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I'm not the first with this error, but I feel like I have tried everything that one can find through searching for the problem. I'm developing a web API with ASP.net core, that's supposed to communicate with my react-native frontend. Problem is, I cannot for the life of me get the connection to work.
program.cs中,我添加了

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    builder.Services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  policy =>
                                  {
                                      policy.AllowAnyMethod();
                                      policy.AllowAnyHeader();
                                      policy.AllowAnyOrigin();
                                  });
            });

以及

app.UseCors(MyAllowSpecificOrigins);

我试过不向方法本身添加cors

[DisableCors]
[HttpGet("{id}")]
public List<Player> GetPlayers(int id)
{
    return (from c in _context.Player.Take(1)
            where c.PlayerId == id
            select c).ToList();
}

我甚至在Azure上部署了服务器和数据库(反正我迟早都应该这样做),只是希望这样能让我的API正常工作。如果我访问URL并通过该URL运行它,API运行得很好。如果我在本地托管它并通过Web运行,API也能很好地工作。
在Azure上,我已更改cors设置以允许所有操作:

如果我同时在本地运行API,我甚至可以通过expo web访问它。但我也需要能够通过我的手机来访问,或者至少通过一个android模拟器来访问。这两种方法都不适用于本地托管的服务器,也不适用于Azure上的服务器。
我该如何解决这个问题?

zujrkrfu

zujrkrfu1#

实际上,在设置了Azure cors设置后不久,它确实开始工作了。最后,我至少可以演示一下。不幸的是,我仍然没有解决方案来解决本地托管时的问题。

相关问题