我在用着Angular 6+
对于一个展示CRUD
to a SQL Database
。我知道Angular
is a client-side framework
所以我使用创建了一个网络服务Visual Studio 2017
我使用的项目是web application ASP.NET Core
因为我正在测试它localhost
, Angular
跑过去4200 port
我的服务目前正在运行port 53819
因此,我(或最后尝试)启用Cross-Origin Resource Sharing (CORS)
通过在我的设备上安装 CORS NUGet 包webservice
并在控制器级别启用它,如下所示:
...
namespace CIE_webservice.Controllers
{
[Produces("application/json")]
[Route("api/CIE")]
[EnableCors(origins: "http://localhost:4200/", headers: "*", methods: "*")]
public class CIEController : Controller
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
...
on my Angular App
我正在使用一个简单的ajax
请求如下:
$.ajax({
url: 'http://localhost:53819/api/CIE/',
success: function() { console.log(" OK "); },
error: function() { console.log(" Error "); }
});
据我可以获得的教程,我的代码没问题,但仍然收到错误:
Failed to load http://localhost:53819/api/CIE/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
即使 Ajax 请求有一个响应 200 OK 并且预览显示了响应 json:
也许我错过了一些东西,或者我没有很好地理解这个概念......如果需要更多信息来解决我的案例,请随时询问。
提前致谢。