【问题标题】:Fail to send data back to React无法将数据发送回 React
【发布时间】:2023-03-07 11:23:01
【问题描述】:

我是 React 和 Node js 的新手。我已经定义了一个函数,它使用子进程从我的 Node.js 应用程序运行 Python 脚本,并且我有一个名为 pythonExecute 的路由器帖子并将结果返回给 做出反应。路由器似乎无法使用react.json(data) 将数据发送回做出反应,有人可以帮忙看看我做错了什么以及如何解决它吗?

功能

const pythonExecute = (data, input) => {
    const res = {
      err: false,
      msg: ""
    }
    return new Promise((resolve, reject)=>{
        const fileName = "test.py"
        saveFile(fileName, data)
          .then(()=>{
              const filePath = path.join(__dirname,"../test.py")
              const spawn = require("child_process").spawn;
              const pythonProcess = spawn('python',[filePath]);   
              pythonProcess.stdout.on('data', (data) => {
                console.log(data.toString());
                resolve(data)
            });
          })
          .catch(()=>{
            console.log("ERROR SAVE FILE"+ saveFileRes)
            const err = {
              err: true,
              output: "Internal Server Error!"
            }
            resolve(err)
          })
    })

快速路由器

const execute = require('../../compile/compile')
router.post('/submit', (req,res)=>{
    console.log(req.body)
    const code = req.body.code
    const input = req.body.input
    const lang = req.body.lang
    return execute.pythonExecute(code, input)
    .then(data=>{
    console.log("SUCCESSFULL PROMISE " + data)
    console.log("SENDING " + data)
    res.write(data)
    deleteFile(path.join(__dirname, '../../test.py'))
    })
    .catch(err => {
    console.log("ERROR PROMISE " + err)
    deleteFile(path.join(__dirname, '../../test.py'))
})
    }  
)

反应

export default class Ide extends Component {
    state={
        code: code.cpp,
        result: 'Submit Code to See Result',
        lang: 'cpp'
    }

    onSubmitHandler = (e) => {
        e.preventDefault()
        alert("submit code")
        axios.post(`${secret.url}code/submit`,this.state)
            .then(res=>{
                console.log(res.data)
                const data = res.data
                if(data.err){
                    // Error in user code
                    this.setState({
                        result: data.error
                    })
                }else{
                    this.setState({
                        result: data.output
                    })
                }

            })
            .catch(err=>{
                console.log(err)
            })
    }

日志

Server started at port 8000
{
  code: '# Your code will come here\nprint("b")',
  result: 'Submit Code to See Result',
  lang: 'python'
}
SAVING FILES
The file was saved!
FILE PATH >> \ide-server\test.py
[6 7 8]

SUCCESSFULL PROMISE [6 7 8]

SENDING [6 7 8]

File deleted!
SORRY NOT DELETED
File deleted!
File deleted!

【问题讨论】:

  • do console.log(res.data) output { code: '# 你的代码会来这里\nprint("b")', result: '提交代码查看结果', lang: '蟒蛇'}?

标签: javascript node.js reactjs express react-router


【解决方案1】:

如果你想发送一个JSON 结构来响应应用程序尝试在服务器上做:

res.send(JSON.stringify(data)) 

数据必须像 {values: [6, 7, 8]} 或其他类似的东西

在客户端:

axios.post(`${secret.url}code/submit`,this.state)
  .then(res=> res.json())               
  .then(result => console.log(result))
  ...            

如果您想发送plain text

res.send(data) 

在客户端:

axios.post(`${secret.url}code/submit`,this.state)
  .then(res=> res.text())               
  .then(result => console.log(result))
  ...            

别忘了在res.write()之后使用res.end()

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 2018-12-18
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    相关资源
    最近更新 更多