【发布时间】:2021-06-24 08:47:16
【问题描述】:
我正在使用以下代码从 python 脚本中获取值。当我在单独的文件中运行它时,它可以完美运行:
var spawn = require('child_process').spawn;
const process = spawn('python', ['src/components/BTC_NT.py']);
process.stdout.on('data', data => {
test = data.toString();
});
process.stderr.on('data', (data) => {
console.log('err results: %j', data.toString('utf8'))
});
process.stdout.on('end', function(){
console.log(test);
});
但是当我像这样在我的 React 应用程序中运行它时:
import React from "react";
import { useState } from "react";
const Main = () => {
const [Text, setText] = useState('');
const [showPrice, setShowPrice] = useState('');
const getVal = (e) => {
e.preventDefault();
var spawn = require('child_process').spawn;
const process = spawn('python', ['src/components/BTC_NT.py']);
process.stdout.on('data', data => {
test = data.toString();
});
process.stderr.on('data', (data) => {
console.log('err results: %j', data.toString('utf8'))
});
process.stdout.on('end', function(){
console.log(test);
setShowPrice(test);
});
}
return(
<div className="Main">
<p>
The following cryptocurrencies are available: Bitcoin(BTC), Ethereum(ETH).
</p>
<form onSubmit={getVal}>
<label htmlFor="CurrencyName">Currency Name: </label>
<input type="text" className="CurrencyName" value={Text} onChange={(e) => setText(e.target.value)} />
<button style={{marginLeft:"5px"}} type="submit">Submit</button>
</form>
{showPrice !== '' && showPrice}
</div>
)
}
export default Main;
我收到错误消息 - “TypeError: spawn is not a function”。
对此的任何帮助将不胜感激。
【问题讨论】:
-
Node-specific JS 不能在浏览器中使用。
标签: javascript node.js reactjs forms