很难传递一些数据来表达。我正在尝试发送从表单收集的一些数据。任何指针将不胜感激。
Express:
app.post('/something-to-post', cors(corsOptionsDelegate), (req, res)=> {
console.log('data:', req.data); // this is always undefined
});
反应
import React from "react";
import axios from "axios";
const Form = () => {
function post(event){
event.preventDefault();
let name = document.getElementById('full-name').value;
let data = {
name: name,
};
axios.post('http://localhost:9000/something-to-post', data)
.then(response => {
// todo
})
.catch(error => {
// todo
})
}
}
return (
<form onSubmit={post}>
<input id="full-name" type="text"/>
<button type="submit">Submit</button>
</form>
)
};
export default Form;
因此,您需要采取这种反应方式,即在这样的状态下跟踪数据:
首先添加一个功能来更新数据handleInputChange
。然后将名称属性添加到输入中,您需要更新该值。检查以下内容,详细了解React forms
import React from "react";
import axios from "axios";
const Form = () => {
const [values, setValues] = React.useState({fullName: ''})
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
setValues({ ...values, [name]: value })
}
function post(event){
event.preventDefault();
let name = document.getElementById('full-name').value;
let data = {
name: values.fullName,
};
axios.post('http://localhost:9000/something-to-post', data)
.then(response => {
// todo
})
.catch(error => {
// todo
})
}
}
return (
<form onSubmit={post}>
<input id="fullName" name="fullName" type="text" value={values.fullName} onChange={(evt)=>this.handleInputChange(evt)} />
<button type="submit">Submit</button>
</form>
)
};
export default Form;
您的代码中有许多错误(语法和语义上的错误,要解决所有这些问题,我会将您的代码示例重构为某种形式,例如:
const { render } = ReactDOM,
{ useState } = React
const Form = () => {
const [fullName, setFullName] = useState(''),
onFullNameChange = ({target:{value}}) => setFullName(value),
onPost = event => {
event.preventDefault()
axios.post('http://localhost:9000/something-to-post', {name: fullName})
}
return (
<form onSubmit={onPost}>
<input type="text" name="fullName" onChange={onFullNameChange} />
<input type="submit" value="Submit" />
</form>
)
};
render (
<Form />,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.1/axios.min.js"></script><div id="root"></div>