[英]How to connect backend create user function to front end (Node.js, React.js, MongoDB)
我正在努力弄清楚如何在创建用户时拥有一个与我的后端相对应的前端。 我已经成功地创建了一个用户(可以使用 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);
向 API 发送请求:
import axios from 'axios'
axios({
method: 'post',
url: '/api/users',
data: {
name: 'John',
email: 'john@example.com',
password: 'Something'
}
});
例如,您可以使用 axios,一个流行的库: https://github.com/axios/axios
axios.post("URL", { email: "myemail@mail.com" })
您应该做的是,将用户在前端输入的信息存储在一个变量中,然后通过post
方法将此数据传递给 fetch 的 function。
// 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 ,因为它在大多数浏览器中都是原生的。
您需要从frontend
(反应)向服务器( API ENDPOINT URL
)发送POST
请求,您可以使用fetch api
或axios
来实现
使用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
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.