面对有关填充javascript数组的问题

问题描述 投票:1回答:1

我一直在致力于创建一个node.js服务器的项目中,我必须从文件中读取一些文本。然后,我想使用Python API来消耗这些文本并返回结果。我已经能够使用这些API并成功获得响应。

[到目前为止,我做了什么-1.创建一个节点服务器2.读取所有文件并从中获取文本内容3.使用适当的API创建Flask服务器4.点击这些API以获得响应

app.js

var bodyParser = require('body-parser');
var request = require('request-promise');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', function(req, res){
    res.send('Node server')
})

app.get('/postdatatoFlask', function (req, res) {
    var fs = require('fs');
    categories = ['business', 'entertainment']

    // answers SHOULD CONTAIN ALL THE RESPONSES FROM THE FLASK API
    var answers = []

    //iterating over different file 
    categories.forEach(function(category){

        for(var i=100;i<=100;i++){

            //creating the path for the new file to be read 
            var path = 'dataset/'+category+'/'+i.toString()+'.txt';

            //textContent contains the data read from file 
            var textContent = fs.readFileSync(path, 'utf8')

            //creating the object 
            var data = { content : textContent }

            //posting the data to the flask server on route postdata
            var options = {
                method: 'POST',
                uri: 'http://127.0.0.1:5000/postdata',
                body: data,
                json: true 
            };

            // returndata is the variable contains the data return by flask API
            var returndata
            var sendrequest = request(options)
            .then(function (parsedBody) {
                 // parsedBody contains the data sent back from the Flask server
                returndata = parsedBody;
                answers.push(returndata)
                console.log(returndata) // do something with this data, here I'm assigning it to a variable.
            })
            .catch(function (err) {
                console.log(err);
            });
        }
    })


    console.log('Showing the responses!!!')
    console.log(answers)
    console.log('Stoping the showcase!!!!')

    res.send('done');
});

app.listen(3000);

compute.py

import json
import time
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
import pandas as pd

app = Flask(__name__)

@app.route('/')
def index():
    return "Flask server"

@app.route('/postdata', methods = ['POST'])
def postdata():
    data = request.get_json()
    # print(data['content'])
    textContent = data['content']
    print(textContent)
    print('-- --- -- --- -- -- -- -- -- --')
    return json.dumps({"newdata":textContent})

if __name__ == "__main__":
    app.run(port=5000)

问题1.在app.js中,我要将所有响应存储在answer数组中,但是无法填充它。2.为什么在console.log(answer)

之后打印console.log(returndata)的输出
javascript python node.js flask
1个回答
0
投票
  1. 使用answers.push(returndata),您正在将一个数组推入另一个数组中。如果要将returndata的内容连接到answers,请使用answers.push(...returndata)

  2. Javascript具有异步,无阻塞的IO运行时,因此在这里:

var sendrequest = request(options)
            .then(function (parsedBody) {
                 // parsedBody contains the data sent back from the Flask server
                returndata = parsedBody;
                answers.push(returndata)
                console.log(returndata) // do something with this data, here I'm assigning it to a variable.
            })

then内部的回调在这些之后被放入调用栈:

console.log('Showing the responses!!!')
    console.log(answers)
    console.log('Stoping the showcase!!!!')

推荐问答