【发布时间】:2021-05-25 06:51:03
【问题描述】:
我正在尝试将数据从我的前端发送到我的后端(React 和 NodeJS)
export default function UserFormPage(){
const [ username, setUsername ] = useState("")
const [ password, setPassword ] = useState("")
// MOVE TO A SERVICE
const setUsernameValue = (e) => {
setUsername(e.target.value)
}
const setPasswordValue = (e) => {
setPassword(e.target.value)
}
// MOVE TO A SERVICE
const handleSubmit = (e) => {
e.preventDefault()
const data = {username, password}
console.log(data)
return fetch("http://localhost:8080/users", {
method: "POST",
mode: "no-cors",
headers: { "Content-Type" : "application/x-www-form-urlencoded"},
body: data
})
}
return(
<div>
<form encType="application/x-www-form-urlencoded" onSubmit={handleSubmit}>
<input value={username} onChange={setUsernameValue} name="username" type="text"/>
<input value={password} onChange={setPasswordValue} name="password" type="text" /*CAMBIAR TYPE A PASSWORD*//>
<button type="submit">Submit</button>
</form>
</div>
)
}
我的后端是
app.post("/users", (req, res) => {
console.log(req.body)
res.send("working");
});
但是 console.log 只显示一个空对象。我测试了使用 Postman 发送 POST 请求,它工作正常,所以问题出在我的前端
【问题讨论】:
-
可能是一个有效的 JSON 字符串。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…您是否在浏览器中检查过您发送的内容并将其与 Postman 中的内容进行比较?
-
你为什么要退回你的提取物?您需要像上面的评论一样使用 JSON.stringify 。或者使用像 axios 这样的库来为你处理这个问题
标签: node.js json reactjs forms enctype