0

I am learning Angular and I am trying to get data from a node js service with the help of the services in angular 2.

when I executed node js services from browser I am able to see the result but when I trying to get data in angular it throws an error.

Here I have created service in node js and from angular, I am trying to get data but it throws an error.

node js:

    var http = require("http");
    var express = require('express');
    var app = express();
    var sql = require('mssql');
    var data;
    var config = {
        server: 'INBGMW-C037',
        database: 'InvoiceReminders',
        user: 'sa',
        password: 'psi'
    };
    app.get('/serviceline_dtl', function (req, res) {
        // connect to your database
        sql.close();
        sql.connect(config, function (err) {
            if (err) console.log(err);
            // create Request object
            var request = new sql.Request();
            request.input('p_Flag', sql.VarChar, "ALL_SERVICE_LINE")
            request.output('po_Retval',sql.Int)
            request.output('po_UpdatedBy',sql.VarChar)
            request.output('po_UpdatedTime',sql.DateTime)
            request.output('po_Message',sql.VarChar)
            // query to the database and get the records
            request.execute("[dbo].[ARA_SP_DS_GetAllSLDetails]").then(function(recordSet) {
                if (recordSet == null || recordSet.length === 0)
                    return;
                // res.send(recordset);
                data=recordSet.recordsets;
                res.send(JSON.stringify(data));
                console.log(data);
                sql.close();
            })
                .catch(function (err) {
                console.log(err);
                sql.close();
            });
        });

    });
    var server = app.listen(5000, function () {
        console.log('Server is running..');
    });

Angular

    import { Injectable } from '@angular/core';

    import { Http, Response, Headers, RequestOptions } from '@angular/http';

    import { serviceLine } from './models/serviceLine';

    import {Observable} from 'rxjs/Rx';

    // Import RxJs required methods
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';

    @Injectable()
    export class HttpService {
        private BASE_URL:string = 'http://localhost:5000/serviceline_dtl';
    constructor(
        private http: Http)
    {
    }

    public getServiceLinedtl(){
        return this.http.get(`${this.BASE_URL`)
            .map((res:Response) => res.json());
        //.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
    }

    }

component:

    import {
        Component,OnInit ,OnChanges
    }
    from '@angular/core';
    import {
        IMyDpOptions
    }
    from 'mydatepicker';
    import {
        HttpService
    }
    from './http.service';
    @Component({
        selector: 'my-app',
        styleUrls:['/css/home.css'],
        templateUrl:'./SpotCheckStatus.html',
        providers:[HttpService]
    })
    export class SpotCheckStatusComponent  implements OnInit
    {
        constructor(
        private httpService: HttpService)
        {
        }

        ngOnInit(){
            this.httpService.getServiceLinedtl().subscribe(
                response=> {
                    console.log("VALUE RECEIVED: ",response);
                }
                ,
                error=> {
                    console.log("ERROR: ",error);
                }
                ,
                () => {
                    console.log("Completed");
                });
        }

    }

the error

Response headers : Headers {_headers: Map(0), _normalizedNames: Map(0)} ok : false status : 0 statusText : "" type : 3 url : null

_body : ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …} proto : Body

8
  • 1
    what error get's thrown Commented Aug 31, 2017 at 12:53
  • Response headers : Headers {_headers: Map(0), _normalizedNames: Map(0)} ok : false status : 0 statusText : "" type : 3 url : null _body : ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …} proto : Body Commented Aug 31, 2017 at 12:55
  • above one is the response which i get Commented Aug 31, 2017 at 12:55
  • is your angular app running at the same port of your node server? Commented Aug 31, 2017 at 12:59
  • 1
    it is possible that you're facing CORS problem...look at this enable-cors.org/server_expressjs.html Commented Aug 31, 2017 at 13:08

1 Answer 1

2

Just in case someone else came to this question: When you have front-end and back-end running on different ports/domain (in this question, I assume you're using angular-cli so the default domain is http://localhost:4200) and the server is running in http://localhost:5000, you should enable CORS to be able to reach the server. If you're using express (as the OP) check this link to enable cors in your node server: https://enable-cors.org/server_expressjs.html

Kind regards.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.