【问题标题】:Angular2 http get request returns htmlAngular2 http get 请求返回 html
【发布时间】:2017-05-13 00:38:31
【问题描述】:

我正在尝试将此测试数据从我的节点 js 服务器发送到前端。

router.get('/abc', (req, res) => {
  return res.json({
   test: "success!"
  });
});

在我的服务组件中:

private url = "http://localhost:4200/auth/abc";

getTitles() {
    return this.http.get(this.url)
    .map(res => res.json());
}

我所期望的是我的测试对象,但最终以字符串格式获取了我的 index.html 文件:(这是我使用 console.log(res) 时得到的)。

<"!DOCTYPE html">...<"/html">

仅供参考,我在 node js 应用程序中使用 cors 模块。

加(我的 angular-cli.json 文件):

 {
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "angular-app"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

【问题讨论】:

  • 不确定,但是当我执行res.json 时,我执行的是{ "asd": "asd" },而不是{ asd: "asd" }。不知道有多大帮助,但你可以试试
  • 感谢 Giora Guttsait 的评论,但对我没有帮助..
  • 您指向的是 webpack 开发服务器,而不是带有您的 api 端点的服务器。您是否在开发服务器上设置了代理?如果没有,那么 api 在哪里运行?指向那里。
  • Neil,我目前正在使用 angular-cli,我想问您如何为这种情况设置代理设置(angular-cli.json)!
  • 您是否尝试过使用 REST 客户端调用“localhost:4200/auth/abc”,或者只是访问浏览器中的 URL(因为它是 GET)?它返回 JSON 还是 HTML?如果它返回 html,则需要调试 API。

标签: json angular angular2-services


【解决方案1】:

您的路由问题,根据我所见,您的快递正在等待 "http://localhost:4200/abc" 返回 "success!" ,但在您的 Angular2 内部,您正试图点击 "http://localhost:4200/auth/abc";

尝试直接点击你的url,看看能不能得到结果,

尝试将其放入浏览器中:

  http://localhost:4200/abc

如果你得到你的 JSON,你的路由器是好的,你只需要在你的应用程序中修复 url。

【讨论】:

  • 对不起,米拉德,我上面没有提到,但我使用的是名为 'auth' 的后端路由器,所以事实并非如此..
  • 所以您可以在 Angular2 之外访问该 URL?
  • 你说的“在 Angular2 之外”是什么意思,米拉德?
  • 我的意思是当你尝试把这个:localhost:4200/auth/abc,在你的浏览器中,你得到你正在寻找的响应吗?
  • 我收到“无 url 段”错误,因为它不是我的角度路线的一部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-08
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
相关资源
最近更新 更多