注冊.js
const Signup = () => {
const [username, Username] = useState("");
const [password, Password] = useState("");
const Post = () => {
fetch("/signup", {
method: "post",
headers: {
"Content-Type":"application/json",
"Accept":"application/json",
},
body: JSON.stringify({
username: "",
password: "",
})
})
.then(response => response.json())
.then(data => {
console.log(data)
})
}
return (
<div>
<input type="text" placeholder="username" value={username} onChange={ (e) => Username(e.target.value) }/>
<br/>
<input type="text" placeholder="password" value={password} onChange={ (e) => Password(e.target.value) }/>
<br/>
<button id="submit_button" onClick={ () => Post() }>Sign up</button>
</div>
)
}
來自后端的 auth.js 函式
router.post("/signup", (request, response) => {
const username = request.body.username;
const password = request.body.password;
// If missing a field: error
if (!username || !password) {
response.status(422).json({ error: "Please add all fields" })
}
// Checks if there already exists an account with that username
user.findOne({ username: username })
.then ((saved_user) => {
if (saved_user) {
return response.status(422).json({ error: "There already exists an account with that username"})
}
})
// Creates a new user and saves the account
const user = new user({ username, password })
user.save()
.then(user => {
response.json({ message: "Account Saved Sucessfully"})
})
.catch(error => {
console.log(error)
})
})
有誰知道出了什么問題?由于某種原因,我從 signup.js 發布的 json 物件似乎是未定義的主體。不過,我已經在函式的前面將 username 宣告為常量。IDK如何解決這個問題。
uj5u.com熱心網友回復:
解決了。忘記App.use(express.json());在路由之前添加。
uj5u.com熱心網友回復:
您沒有在正文中提供用戶名和密碼
body: JSON.stringify({
username: "",
password: "",
}).
const Signup = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const Post = () => {
fetch("/signup", {
method: "POST",
headers: {
"Content-Type":"application/json",
"Accept":"application/json",
},
body: JSON.stringify({
username: username,
password: password,
})
})
.then(response => response.json())
.then(data => {
console.log(data)
})
}
return (
<div>
<input type="text" placeholder="username" value={username} onChange={ (e) => setUsername(e.target.value) }/>
<br/>
<input type="text" placeholder="password" value={password} onChange={ (e) => setPassword(e.target.value) }/>
<br/>
<button id="submit_button" onClick={ () => Post() }>Sign up</button>
</div>
)
}
嘗試這樣使用,也許它可以作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/353505.html
標籤:javascript 表达
