【问题标题】:Browser displays err_empty_response after http requesthttp请求后浏览器显示err_empty_response
【发布时间】:2019-08-26 16:30:02
【问题描述】:

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

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

GET http://localhost:4200/api/test net::ERR_EMPTY_RESPONSE core.js:1673 错误 HttpErrorResponse {标头:HttpHeaders,状态:0, statusText: "未知错误", url: null, ok: 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 路由.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 服务.ts

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

【问题讨论】:

    标签: node.js angular express


    【解决方案1】:

    我相信你在这个街区的问题

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

    【讨论】:

    • 太棒了。我只是添加了 async() 的 asyncHandler。它似乎正在工作。或者为什么我应该使用 asyncHandler?
    • 没关系,你不需要asyncHandler
    猜你喜欢
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 2010-12-21
    • 2012-07-15
    • 2016-06-15
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    相关资源
    最近更新 更多