英文:
How do I modify POST request in Account.jsx file?
问题
这是您的代码的翻译:
我正在开发一个个人项目员工管理系统,并在发送POST请求时遇到问题。该项目使用MERN(MongoDB、Node.js和React.js)。以下是项目链接 https://github.com/Mbicha/employee_management_system,以及[显示错误的图片][1]
[1]: https://i.stack.imgur.com/0LT1c.png
代码如下:
Account.jsx
```jsx
import React, { useState } from "react";
import { Link } from "react-router-dom";
import http from "../http-common";
const Account = () => {
const [formData, setFormData] = useState({
first_name: "", last_name: "", email: "", phone: "", password: ""
});
const handleFormChange = (event) => {
setFormData(prev => ({
...prev,
[event.target.name]: event.target.value
}));
}
const handleSubmit = async (event) => {
event.preventDefault();
try {
const options = {
headers: {
'Content-Type': 'application/json',
},
};
await http.post('/user', formData, options);
console.log("已保存");
event.target.reset();
} catch (error) {
console.log(error);
}
}
return (
<div>
<div className="flex flex-col justify-center items-center">
<form className="flex flex-col items-center rounded-lg shadow-md p-2 w-full sm:w-2/3 md:w-1/3 lg:w-1/3">
<h1 className="text-center text-green-700 text-2xl mb-4">账户</h1>
<input className="border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700" type="text" placeholder="名字" name='first_name' onChange={handleFormChange}/>
<input className="border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700" type="text" placeholder="姓氏" name='last_name' onChange={handleFormChange}/>
<input className="border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700" type="email" placeholder="电子邮件" name='email' onChange={handleFormChange}/>
<input className="border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700" type="text" placeholder="电话" name='phone' onChange={handleFormChange}/>
<input className="border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700" type="password" placeholder="密码" name='password' onChange={handleFormChange}/>
<button className="bg-green-700 hover:bg-green-600 text-white font-bold p-2 rounded focus:outline-none focus:shadow-outline w-4/5 mb-4" type="button" onClick={handleSubmit}>注册</button>
<span>已经有账户? <Link to='/'>登录</Link></span>
</form>
</div>
</div>
)
}
export default Account;
http-common.js
import axios from "axios";
export default axios.create({
baseURL: "http://localhost:5000/api",
headers: {
"Content-type": "application/json"
}
});
server.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const cookie = require('cookie-parser');
require('./config/db.config');
const auth = require('./routes/route_auth');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookie());
// 路由
app.use('/api/user', auth);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`服务器正在运行在 ${PORT}`);
});
route_auth.js
const express = require("express");
const router = express.Router();
const user = require("../controllers/auth");
router.post('/', user.register);
module.exports = router;
auth.js(控制器)
const user = require("../models/user");
const utils = require("../utils");
exports.register = async(req, res) => {
try {
const hashed = utils.hashPassword(req.body.password, 10);
const newUser = new user({
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
phone: req.body.phone,
password: hashed
});
await newUser.save();
res.status(201).json(newUser);
} catch (error) {
res.status(404).send({ error:error });
}
}
// 所有用户
exports.getUsers = async(req, res) => {
try {
const users = await user.find({});
res.send({ users })
} catch (err) {
res.status(400).send({err: err});
}
};
// 根据id获取用户
module.exports.getUserById = async (req, res) => {
try {
const user = await user.findById(req.params.id);
res.send({ user });
} catch (error) {
res.status(404).send({ message: `未找到用户` });
}
}
user.js(模型)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const user = new Schema({
first_name: {type: String, required: true},
last_name: {type: String, required: true},
email: {type: String, required: true},
phone: {type: String, required: true},
password: {type: String, required: true}
});
module.exports = mongoose.model("user", user);
db.config.js
const mongoose = require("mongoose");
const uri = "mongodb://127.0.0.1:27017/employees_db";
// 允许使用Promise
mongoose.Promise = global.Promise;
// 连接
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology:true });
// 验证
mongoose.connection
.once('open', () => console.log('已连接到数据库!'))
.on('error', err => console.log('数据库发生错误!', err));
utils.js
const bycrypt = require('bcrypt');
// 哈希方法
const hashPassword = (password, rounds) => {
const salt = bycrypt.genSaltSync(rounds);
const hashedPassword = bycrypt.hashSync(password, salt);
return hashedPassword;
}
错误发生在Account.jsx,当我向数据库发送数据时出现“http://localhost:5000/api/user 404 (未找到)”错误。
<details>
<summary>英文:</summary>
I am working on a personal project Employee Management System and am stuck on sending POST request. The project is using MERN (MongoDB, nodejs, and reactjs). The following is the project link https://github.com/Mbicha/employee_management_system, and [Image showing error][1]
[1]: https://i.stack.imgur.com/0LT1c.png
Codes are as follows:
Account.jsx
import React, { useState } from "react";
import { Link } from "react-router-dom";
import http from "../http-common";
const Account = () => {
const [formData, setFormData] = useState({
first_name: "", last_name: "", email: "", phone: "", password: ""
});
const handleFormChange = (event) => {
setFormData(prev => ({
...prev,
[event.target.name]: event.target.value
}));
}
const handleSubmit = async (event) => {
event.preventDefault();
try {
const options = {
headers: {
'Content-Type': 'application/json',
},
};
await http.post('/user', formData, options);
console.log("Saved");
event.target.reset();
} catch (error) {
console.log(error);
}
}
return (
<div>
<div className="flex flex-col justify-center items-center">
<form className="flex flex-col items-center rounded-lg shadow-md p-2 w-full sm:w-2/3 md:w-1/3 lg:w-1/3">
<h1 className="text-center text-green-700 text-2xl mb-4">Account</h1>
<input className="border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700" type="text" placeholder="First Name" name='first_name' onChange={handleFormChange}/>
<input className="border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700" type="text" placeholder="Last Name" name='last_name' onChange={handleFormChange}/>
<input className="border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700" type="email" placeholder="Email" name='email' onChange={handleFormChange}/>
<input className="border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700" type="text" placeholder="Phone" name='phone' onChange={handleFormChange}/>
<input className="border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700" type="password" placeholder="Password" name='password' onChange={handleFormChange}/>
<button className="bg-green-700 hover:bg-green-600 text-white font-bold p-2 rounded focus:outline-none focus:shadow-outline w-4/5 mb-4" type="button" onClick={handleSubmit}>Register</button>
<span>Already have an account? <Link to='/'>Login</Link></span>
</form>
</div>
</div>
)
}
export default Account;
http-common.js
import axios from "axios";
export default axios.create({
baseURL: "http://localhost:5000/api",
headers: {
"Content-type": "application/json"
}
});
server.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const cookie = require('cookie-parser');
require('./config/db.config');
const auth = require('./routes/route_auth');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookie());
//routes
app.use('/api/user', auth);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on ${PORT}`);
});
route_auth.js
const express = require("express");
const router = express.Router();
const user = require("../controllers/auth");
router.post('/', user.register);
module.exports = router;
auth.js // controller
const user = require("../models/user");
const utils = require("../utils");
exports.register = async(req, res) => {
try {
const hashed = utils.hashPassword(req.body.password, 10);
const newUser = new user({
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
phone: req.body.phone,
password: hashed
});
await newUser.save();
res.status(201).json(newUser);
} catch (error) {
res.status(404).send({ error:error });
}
}
// All users
exports.getUsers = async(req, res) => {
try {
const users = await user.find({});
res.send({ users })
} catch (err) {
res.status(400).send({err: err});
}
};
// User by id
module.exports.getUserById = async (req, res) => {
try {
const user = await user.findById(req.params.id);
res.send({ user });
} catch (error) {
res.status(404).send({ message: `User is not found` });
}
}
user.js // model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const user = new Schema({
first_name: {type: String, required: true},
last_name: {type: String, required: true},
email: {type: String, required: true},
phone: {type: String, required: true},
password: {type: String, required: true}
});
module.exports = mongoose.model("user", user);
db.config.js
const mongoose = require("mongoose");
const uri = "mongodb://127.0.0.1:27017/employees_db"
// Allow Promises
mongoose.Promise = global.Promise;
// Connection
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology:true });
// Validation
mongoose.connection
.once('open', () => console.log('Connected to the database!'))
.on('error', err => console.log('Error with the database!', err));
utils.js
const bycrypt = require('bcrypt');
// Hash Method
const hashPassword = (password, rounds) => {
const salt = bycrypt.genSaltSync(rounds);
const hashedPassword = bycrypt.hashSync(password, salt);
return hashedPassword;
}
Error is in occurring in Account.jsx when I send a data to the database "http://localhost:5000/api/user 404 (Not Found)"
</details>
# 答案1
**得分**: 0
404错误代码表示没有与`/api/user`相关的终端点。
```javascript
// 在 server.js 文件中
// 路由
app.use('/api/user', auth);
// 在 routes/route_auth.js 文件中
router.post('/', user.register);
我认为你的正确终端点路径是 /api/user/
,需要添加斜杠。
英文:
404 Error code means that there is no endpoint which is related to /api/user
.
// In the server.js
//routes
app.use('/api/user', auth);
// routes/route_auth.js
router.post('/', user.register);
I think your correct endpoint path is /api/user/ <- add trailing slash
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论