Search code examples
jsonangularangular2-services

Angular2 http get request returns html


I'm trying to send this test data from my node js server to front end.

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

In my service component:

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

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

What I expected was my test object but ends up getting my index.html file in string format: (that's what I get when I use console.log(res)).

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

FYI, I'm using cors module in node js app.

plus(my angular-cli.json file) :

 {
  "$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": {}
  }
}

Solution

  • The problem with your routing, based on what I can see, your express is waiting for "http://localhost:4200/abc" to return "success!" , but inside your Angular2 you're trying to hit "http://localhost:4200/auth/abc";.

    Try hitting your url directly to see if you can get the result ,

    try putting this in the browser :

      http://localhost:4200/abc
    

    If you get your JSON back , your router is good, you just need to fix the url in your app.