HTTP请求后浏览器显示err_empty_response

时间:2019-04-04 20:01:49

标签: node.js angular express

我通过Node.js启动Python程序,并将请求发送到服务器。 Python程序运行后,我想在客户端输出数据。 Python需要很长时间,但有时会标出数据。

一段时间后,我在浏览器中收到以下错误消息:

  

获取http://localhost:4200/api/test净值:: ERR_EMPTY_RESPONSE   core.js:1673错误HttpErrorResponse {标头:HttpHeaders,状态:0,   statusText:“未知错误”,网址:null,确定:false,...}

但是我的Python程序通过了。

我尝试使用res.end(),res.send(200).json()和res.send(),但是遇到了同样的问题

server.ts

import app from './app';
import { Database } from './database';

const PORT = 8000;

Database.connect();

app.listen(PORT, () => {
  console.log('Express server listening on port ' + PORT);
});

app.timeout = 12000000000;

Node.js route.ts

app.route('/api/test').get((req: Request, res: Response) => {
  const spawn = require('child_process').spawn;
  const ls = spawn('python', [__dirname + '/getPosts.py']);
  let inData;
  ls.stdout.on('data', (chunk) => {
    inData = chunk.toString().replace('\n', '').split(',');
  });

  ls.stderr.on('data', (chunk) => {
    console.log(`stderr: ${chunk}`);
  });

  ls.on('close', (code) => {
    res.json(inData[0]); // -> ['True']
  });
});

Angular service.ts

  callData() {
    return this._http.get<any>(`${'/api/test'}`, {}).pipe(map((res: any) => {
      return res;
    }));
  }

1 个答案:

答案 0 :(得分:0)

我相信您在此区块中遇到的问题

app.route('/api/test').get((req: Request, res: Response, next: any) => {

        |
        |
        |
        |
       \ /
        .

  (1)     // you receive request from front-end.
  (2)     // then excute your paython script/

      const spawn = require('child_process').spawn;
      const ls = spawn('python', [__dirname + '/getPosts.py']);
      let inData;

      // start listning to events for stdout. 

      ls.stdout.on('data', (chunk) => {
        inData = chunk.toString().replace('\n', '').split(',');
      });

      ls.stderr.on('data', (chunk) => {
        console.log(`stderr: ${chunk}`);
      });

      ls.on('close', (code) => {
        res.json(inData[0]); // -> ['True']

        (6) I got data here. send it as json
        (7) Huh!!! where is the connection.

      });


   (3)    // your callback is waiting you to responed
   (4)    // nothing happen 
   (5)    // connection closed.

});




             FIX
// npm install --save express-async-handler
// of use this
const asyncUtil = fn =>
function asyncUtilWrap(...args) {
  const fnReturn = fn(...args)
  const next = args[args.length-1]
  return Promise.resolve(fnReturn).catch(next)
}


  app.route('/api/test', asyncHandler(async (req, res, next) => {
    const inData = await processMydata();
    res.json(inData[0])
})) 

async processMydata(){
      const spawn = require('child_process').spawn;
      const ls = spawn('python', [__dirname + '/getPosts.py']);
      const promise  =  new Promise(function(resolve, reject){
        ls.stdout.on('data', (chunk) => {
          const inData = chunk.toString().replace('\n', '').split(',');
          resolve(inData)
        });
      }) 
    return await promise;;
}