我正在构建一个应用程序,在这个应用程序中,烧瓶rest接受两个字符串,并提供一个浮动值作为预测。现在我正在尝试连接到react应用程序,这样预测就可以显示在网页上了。
目标:从前端获取两个字符串,并使用restapi进行推断,并在前端给出预测值。
下面是用于在react应用程序中获取rest预测的代码。
function App() {
const [state, setState] = useState([{}]);
useEffect(() => {
fetch("/predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O")
.then((res) => res.json())
.then((data) => {
setState(data);
console.log(data);
});
}, []);
在fetch /predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O
中,solute=CC(C)(C)Br
和solvent=CC(C)(C)O
是用于进行预测的烧瓶rest的输入。
但是我想给它从前端,而不是在URL中提到。该怎么做呢?
修改后的代码以获取结果并显示
function App() {
const [state, setState] = useState([{}]);
const [uri, setUri] = useState([{}]);
const [resultstate, setResultState] = useState([{}]);
function HandleSubmit() {
const uri = "http://127.0.0.1:3000/?${form.one}&${form.two}";
setUri(uri);
useEffect(() => {
fetch(uri)
.then((response) => {
if (response.status === 200) {
return response.json();
}
})
.then((data) => {
setResultState(data);
console.log(data);
});
});
}
function handleChange(e) {
const { nodeName, name, value } = e.target;
if (nodeName === "INPUT") {
setState({ ...FormData, [name]: value });
}
}
return (
<div className="App">
<state onChange={handleChange}>
<fieldset>
<legend>Solute</legend>
<input name="one" value={state.one} />
</fieldset>
<fieldset>
<legend>Solvent</legend>
<input name="two" value={state.two} />
</fieldset>
<button type="button" onClick={HandleSubmit}>
Submit
</button>
</state>
<Deploy />
</div>
);
}
运行修改后的代码,我将得到这个错误
发布于 2021-11-10 18:55:46
form
状态。form
状态。form
中的信息创建一个新的URI,然后执行fetch
。
const { useState } = React;
function Example() {
const [ form, setForm ] = useState({});
function handleSubmit() {
const uri = `http://example.com/?${form.one}&${form.two}`;
console.log(`Current state: ${JSON.stringify(form)}`);
console.log(`Fetch URI: ${uri}`);
// fetch(uri)... etc
}
// Because the listener is attached to the form element
// (see "Additional documentation" below)
// check that the element that's been changed is an input
// and then update the state object using the name as a key, and
// adding the value of the input as the object value for that key
function handleChange(e) {
const { nodeName, name, value } = e.target;
if (nodeName === 'INPUT') {
setForm({ ...form, [name]: value });
}
}
// Each input has a name, and maintains its
// value from the form state
return (
<form onChange={handleChange}>
<fieldset>
<legend>Input one</legend>
<input name="one" value={form.one} />
</fieldset>
<fieldset>
<legend>Input two</legend>
<input name="two" value={form.two} />
</fieldset>
<button type="button" onClick={handleSubmit}>Submit</button>
</form>
);
};
ReactDOM.render(
<Example />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
补充文件
https://stackoverflow.com/questions/69922509
复制相似问题