在同一端口上运行Angular和ASP.NET Web API [英] Run Angular and ASP.NET Web API on the same port

查看:87
本文介绍了在同一端口上运行Angular和ASP.NET Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用angular向运行ASP.NET的API服务器发出API调用.但是,对于角度开发,我有一个跨域问题,我正在使用localhost.在生产版本中,它们都将使用IIS在同一域下运行.

有没有办法在ASP.NET的同一端口上运行angular应用程序?

P.S .:对于解决此问题,我也欢迎其他选择.

解决方案

我遇到了同样的问题,然后发现

更新:很久很久没回答,很抱歉.

要解决cors问题(在这种情况下),可以将ng serve命令与代理一起使用.

例如,在我的情况下,我使用了如下的proxy.conf.json文件:

{
  "/api/*": {
    "target": "http://localhost:3000",
    "secure": false,
    "pathRewrite": {"^/api" : ""}
  }
}

此代码将每个对/api/*的请求的URL重写为api正在监听的http://localhost:3000.

因此,为了说明这一点,如果您提出了有角度要求的请求,例如http://localhost:4200/api/users,它将被重定向/重写为http://localhost:3000/api/users,以解决cors问题.

现在,您运行角度应用程序的方式有所不同.

ng serve --proxy-config proxy.conf.json

I am currently using angular to issue API call to an API server running ASP.NET. However, I have a cross-origin issue as for angular development, I am using localhost. While in the production version they will all run under the same domain using IIS.

Is there a way to run the angular app on the same port with ASP.NET?

P.S.: I am also open for other alternatives on solving this issue.

解决方案

I've encountered the same problem, then I've found this post on medium, hope this works for you.

Edit: Actually the solution that I've used is from that article.

The idea is that you can't "publish" the API and the Angular app on the same port, but you can use a proxy to connect from the Angular app to the API on the other port.

Update: sorry for not answering this long time ago.

To deal with the cors issue (in this case) you can use a proxy with the ng serve command.

For example, in my case I have used a proxy.conf.json file like this:

{
  "/api/*": {
    "target": "http://localhost:3000",
    "secure": false,
    "pathRewrite": {"^/api" : ""}
  }
}

This code rewrite the url on every request to /api/* to the http://localhost:3000 where your api is listening.

So, to illustrate, if in angular you make a request like http://localhost:4200/api/users it will be redirected/rewrited to http://localhost:3000/api/users solving the cors issue.

Now, the way you have to run your angular application is different.

ng serve --proxy-config proxy.conf.json

这篇关于在同一端口上运行Angular和ASP.NET Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆