无法在我的Node.js中附加res.send(结果)以将数据发送到角度应用程序

时间:2018-10-10 13:17:20

标签: node.js angular http neo4j

我制作了一个Nodejs和angular2应用程序,需要将它们集成到Neo4j应用程序中。我能够从来自Angular2的NodeJS代码中访问数据库,但是后来我无法将该数据发送回angular2应用程序。如果我给

 res.send(result) 

函数tmsServer中的任何地方,都会出现错误->

 inside catch = Error: Can't set headers after they are sent.

请帮助。我想将数据发送回角度应用程序。

tmservercontroller.js

   // Require Neo4j
   var neo4j = require('neo4j-driver').v1;

  var path = require('path');
  var logger = require('morgan');
  var bodyParser = require('body-parser');
  var express = require('express');

  var router = express.Router();

   var app = express();


  // Create Driver
   const driver = new neo4j.driver("bolt://localhost:11001", 
   neo4j.auth.basic("neo4j", "Virtuallib1"));



 // //View Engine

   app.set('views', path.join(__dirname, 'views'));

   app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(express.static(path.join(__dirname, 'public')));



  var session = driver.session();
  var request = require('request');

   var finalResult ;

   router.post('/', tmsServer);
   module.exports = router;


   function tmsServer(req, res) { 

    session
       .run('MATCH (n) RETURN n LIMIT 5')

       .then(function (result){

           result.records.forEach(function(record){
               console.log("record = ", record);
               console.log("result = ", result)
               console.log("1] 
   record._fields[0].properties=",record._fields[0].properties);


                    res.send(result); 
           });


       })


       .catch(function(err){
        console.log("inside catch = "+err);
    })

    res.send('It Works');
    session.close();
   }

neo4j-primary.component.ts

   import { Component, OnInit } from '@angular/core';
   import { Injectable } from '@angular/core';

 import { ToasterService } from '../toaster.service';

  import { FormGroup, FormControl, FormBuilder, Validators } from 
 '@angular/forms';
   import { Http, Response, Headers } from '@angular/http';
  import { config } from '../config';
  import { Subject } from 'rxjs';

  import 'rxjs/add/operator/map';
  import { map } from 'rxjs/operators';
  import 'rxjs/Rx';
  import { Observable } from 'rxjs';

  // Statics
  import 'rxjs/add/observable/throw';


 @Component({
  selector: 'app-neo4j-primary',
  templateUrl: './neo4j-primary.component.html',
  styleUrls: ['./neo4j-primary.component.css']
  })

 export class Neo4jPrimaryComponent implements OnInit {

 constructor(private http: Http,  private notify: ToasterService) { }

 ngOnInit() {
this.viewNodesStart();
    }


  emptyObj1;
   emptyObj;
   info;

   // -------------------------------  Nodes Entire Data -------------

  viewNodesStart() {

console.log("INSIDE viewNodesStart()")

// Nodes Value

   console.log("inside Nodes Value");
  var data = localStorage.getItem('token');

 console.log("data is=>",data+ "emptyobj1 = "+ this.emptyObj1);

   var url = config.url;
   var port = config.port;

   var object = {
    "emptyObj" : this.emptyObj
    }
    this.http.post("http://" + url+":" + port + 
    "/viewNodesStart",this.emptyObj1)
  .map(Response => Response)
  .subscribe((res: Response) => {

    console.log("XXXXXXXXXXXX Response on /viewNodesStart", res);

    this.info = res;   

    if (this.info.statusCode == 200) {
      console.log("Data added successfully");

    } else {
      console.log("Data is not inserted")

     }
     });

   }

   }

1 个答案:

答案 0 :(得分:2)

您只能发送一次响应,在发送响应“ It works”并再次发送包含实际数据的响应时,您正在运行异步操作。

res.send将响应标头设置为对象,该对象应在请求生命周期中理想发生一次。

function tmsServer(req, res) { 
    session
     .run('MATCH (n) RETURN n LIMIT 5')
     .then(function (result){
       result.records.forEach(function(record){
         // This will execute only when the promise is resolved and data is returned from database.
         res.send(result); // (RES02)
       });
     })
     .catch(function(err){
      console.log("inside catch = "+err);
     })

     res.send('It Works'); // (RES01) <--- This runs before RES02
    session.close();
}

您的答案的解决方案是删除RES01