我正在制作一个计算器应用程序,并且我正在发送数据以表示要进行评估,但出现错误。 handleEqual是单击相等按钮时应进行反应的一种方法,该方法应评估并设置状态。我不理解该错误。我想念什么。谢谢
createError.js:17未捕获(承诺)错误:网络错误 在createError(createError.js:17) 在XMLHttpRequest.handleError(xhr.js:87)
reactjs
import React, { Component } from "react";
import "./App.css";
import { Button } from "./components/Button";
import { Input } from "./components/Input";
import { ClearButton } from "./components/ClearButton";
import * as math from "mathjs";
import axios from "axios";
class App extends Component {
constructor(props) {
super(props);
this.state = {
input: ""
};
}
addToInput = val => {
this.setState({
input: this.state.input + val
});
};
handleEqual = () => {
// input: math.eval(this.state.input)
let num = {
input: this.state.input
};
axios.post("http://localhost:5000/path", num).then(res => {
if (res.status === 200) {
console.log(res.data);
this.setState({
input: res.data
});
console.log("Response:", res.data);
}
});
};
render() {
return (
<div className="app">
<div className="calc-wrapper">
<Input input={this.state.input} />{" "}
<div className="row">
<Button handleClick={this.addToInput}> 7 </Button>{" "}
<Button handleClick={this.addToInput}> 8 </Button>{" "}
<Button handleClick={this.addToInput}> 9 </Button>{" "}
<Button handleClick={this.addToInput}> /</Button>
</div>{" "}
<div className="row">
<Button handleClick={this.addToInput}> 4 </Button>{" "}
<Button handleClick={this.addToInput}> 5 </Button>{" "}
<Button handleClick={this.addToInput}> 6 </Button>{" "}
<Button handleClick={this.addToInput}> - </Button>{" "}
</div>{" "}
<div className="row">
<Button handleClick={this.addToInput}> 1 </Button>{" "}
<Button handleClick={this.addToInput}> 2 </Button>{" "}
<Button handleClick={this.addToInput}> 3 </Button>{" "}
<Button handleClick={this.addToInput}> + </Button>{" "}
</div>{" "}
<div className="row">
<Button handleClick={this.addToInput}> 0 </Button>{" "}
<Button handleClick={this.addToInput}> . </Button>{" "}
<Button handleClick={() => this.handleEqual()}> = </Button>{" "}
</div>{" "}
<div className="row">
<ClearButton
handleClear={() =>
this.setState({
input: ""
})
}
>
CE{" "}
</ClearButton>{" "}
</div>{" "}
</div>{" "}
</div>
);
}
}
export default App;
表达
app.post("/path", (req, res) => {
const val = req.body.input;
console.log(val);
const calc = mathjs.eval(val);
res.writeHead(200, {
"Content-type": "application/json"
});
res.end(JSON.stringify(calc));
});
答案 0 :(得分:0)
根据官方docs,res.end()用于快速结束响应而没有任何数据。如果要向客户端返回值,请使用res.send()。
答案 1 :(得分:0)
如果要获取字符串化的calc对象,则应使用res.data.calc