在axios发布请求上不断收到XML解析错误

时间:2019-08-07 05:52:11

标签: python node.js reactjs express

我正在使用axios进行发布请求,该请求将图片发送到我的服务器。然后即时通讯使用python-shell运行ML脚本,该脚本将json文件输出到我的服务器。我想在完成p​​ython脚本后返回上述json文件。

一切都单独工作,创建json文件,我可以将json文件发送回客户端...只是当我将res.sendFile放在pyshell.end回调中以在python脚本完成时触发时(当前必须刷新页面,这会触发单独的get请求以获取json文件)。

再次看来,当res.sendFile所在的位置时,它出于某种原因而不是application / json发送XML。我试过设置标题。

const fileUpload = require("express-fileupload");
const {
    PythonShell
} = require('python-shell')



ocrDemoRoute.use(fileUpload());

ocrDemoRoute.post("/api/demo/upload", (req, res) => {

    if (Object.keys(req.files).length == 0) {
        return res.status(400).send('No files were uploaded.');
    }

    // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
    let upload = req.files.upload;

    // Use the mv() method to place the file somewhere on your server
    upload.mv('ocrDemo/samples/uploadImage.jpg', function (err) {
        if (err) return res.send(err);
    })


    let options = {
        pythonPath: "/anaconda3/bin/python"
    }

    let pyshell = new PythonShell('./ocrDemo/Task2.py', options);
    let returnMessage = []
    // sends a message to the Python script via stdin

    pyshell.on('message', function (message) {
        // received a message sent from the Python script (a simple "print" statement)
        console.log(message)
        returnMessage.push(message)
    });

    // end the input stream and allow the process to exit
    pyshell.end(function (err, code, signal) {
        if (err) throw err;
        console.log('The exit code was: ' + code);
        console.log('The exit signal was: ' + signal);
        console.log('finished');
        return res.sendFile(path.join(__dirname, "../ocrDemo/new_output_0.json"), {
            headers: {
                'content-type': 'application/json'
            }
        })
    })


})

module.exports = ocrDemoRoute;

在下图中,使用显示的代码发出了最后两个失败的请求。如果我将res.sendFile放在pyshell.end之下或之上的其他任何地方,则成功的代码(200个状态代码和类型为json)。

https://imgur.com/Gwflpxm

0 个答案:

没有答案