无法从节点js服务获取数据到角度js 2

时间:2017-08-31 12:52:34

标签: javascript json node.js angular typescript

我正在学习Angular,我正试图在角度2的服务的帮助下从节点js服务获取数据。

当我从浏览器执行节点js服务时,我能够看到结果,但是当我尝试以角度获取数据时,它会抛出错误。

这里我已经在节点js中创建了服务,并且我正在尝试获取数据,但它会引发错误。

节点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'));
            }

        }

成分:

    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");
                        }

                      );
    }
    }

错误

  

响应标头:标头{_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

1 个答案:

答案 0 :(得分:2)

以防其他人提出这个问题:当你在不同的端口/域上运行前端和后端时(在这个问题中,我假设你使用的是angular-cli,所以默认域是{{ 3}})并且服务器在http://localhost:4200中运行,您应该启用CORS才能到达服务器。如果您正在使用express(作为OP),请选中此链接以在您的节点服务器中启用cors:http://localhost:5000

亲切的问候。