【问题标题】:CORS issues in ionic requesting api hosted on localhost托管在 localhost 上的 ionic 请求 api 中的 CORS 问题
【发布时间】:2026-01-15 19:15:01
【问题描述】:

我的 Ionic 应用程序在 http://localhost:8100/ 上运行,我请求 http://localhost:40410/api/myApi 获取 api。
我知道它会出现 CORS 问题,我尝试在 ionic.config.json 中添加代理设置,例如

"proxies": [
{
  "path": "/api",
  "proxyUrl": "http://localhost:40410/"
}
           ]  

当我 ionic serve 时,我在控制台 Proxy added:/api => https://localhost:44381/ 上得到了这个输出,但是在应用程序中,我无法从 api 获取任何数据。
这就是我在 chrome 开发工具中得到的

Request URL: http://localhost:8100/api/myApi
Request Method: GET
Status Code: 500 Internal Server Error
Remote Address: 127.0.0.1:8100

这是我的 ts 代码,

    this.http.get('/api/myApi').subscribe(
(data) => {
  console.log(data.json());
},(error) =>{
console.log(error);
}
   );

【问题讨论】:

  • 为什么不在服务器端使用 cors()?
  • @Erez.S 我也有类似的问题,能否详细说明如何在服务器端使用 cors()?
  • 运行“npm install cors --save”并将其添加到 app.js 中:app.use('*', cors());
  • @Erez.S app.js ?在离子中你的意思是 app.ts
  • cors 问题是服务器端问题,因此在客户端的 ionic 中使用 cors 可能是一个错误!

标签: api ionic-framework ionic3


【解决方案1】:

您可以使用以下参数运行 chrome 来禁用 cors 保护。 --disable-web-security

【讨论】:

  • 我可以理解,通过禁用网络安全运行 chrome 或在 chrome 中使用 cors Anywhere 插件可以解决问题。
  • 你能告诉我我是否使用 ionic serve -c 运行它,然后在我的手机中查看它是如何运行的?