我正在努力弄清楚如何在創建用戶時擁有一個與我的后端相對應的前端。我已經成功地創建了一個用戶(可以使用 Insomnia 發布到 MongoDB),但不知道在前端創建用戶的結構是什么。這是我的代碼的樣子:
路由器
const express = require('express');
const router = express.Router();
router.post('/', async (req, res) => {
// First Validate The Request
const { error } = validate(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
}
// Check if this user already exisits
let user = await User.findOne({ email: req.body.email });
if (user) {
return res.status(400).send('That user already exisits!');
} else {
// Insert the new user if they do not exist yet
user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
await user.save();
res.send(user);
}
});
module.exports = router;
服務器.js
app.use('/api/users', users);
uj5u.com熱心網友回復:
向此 API 發布請求:
import axios from 'axios'
axios({
method: 'post',
url: '/api/users',
data: {
name: 'John',
email: '[email protected]',
password: 'Something'
}
});
uj5u.com熱心網友回復:
您可以使用 axios,例如一個流行的庫:https ://github.com/axios/axios
axios.post("URL", { email: "[email protected]" })
uj5u.com熱心網友回復:
您應該做的是將用戶在您的前端鍵入的資訊存盤在一個變數中,并通過該post方法將此資料傳遞給 fetch 的函式。
// User information
let username = 'boneless';
// Options for your request
let options = { method: 'POST', body: JSON.stringify({username: username});
let request = await fetch('url', { options });
let response = await request;
// Now you can apply logic to your response. Based on how your server replies.
我建議閱讀fetch,因為它在大多數瀏覽器中都是原生的。
uj5u.com熱心網友回復:
您需要從您的(react)POST向服務器 ( ) 發送請求,您可以使用或API ENDPOINT URLfrontendfetch apiaxios
使用fetch api(示例)-
function createUser(userData) {
try {
const response = await fetch('API_ENDPOINT_URL', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
})
return response.json()
}
catch(error) {
// handle error
}
}
使用 axios - (示例)
function createUser(userData) {
axios.post('API_ENDPOINT_URL', userData)
.then((response)=> {
return response.json()
})
.catch((error)=>{
// handle error
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/461300.html
標籤:javascript 节点.js 反应 mongodb 前端
下一篇:打字稿中的抽象型別類/介面
