如何修改 Account.jsx 文件中的 POST 请求?

huangapple go评论63阅读模式
英文:

How do I modify POST request in Account.jsx file?

问题

这是您的代码的翻译:

我正在开发一个个人项目员工管理系统并在发送POST请求时遇到问题该项目使用MERNMongoDBNode.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 &quot;react&quot;;
import { Link } from &quot;react-router-dom&quot;;
import http from &quot;../http-common&quot;;
const Account = () =&gt; {
const [formData, setFormData] = useState({
first_name: &quot;&quot;, last_name: &quot;&quot;, email: &quot;&quot;, phone: &quot;&quot;, password: &quot;&quot;
});
const handleFormChange = (event) =&gt; {
setFormData(prev =&gt; ({
...prev,
[event.target.name]: event.target.value
}));
}
const handleSubmit = async (event) =&gt; {
event.preventDefault();
try {
const options = {
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;,
},
};
await http.post(&#39;/user&#39;, formData, options);
console.log(&quot;Saved&quot;);
event.target.reset();
} catch (error) {
console.log(error);
}
}
return (
&lt;div&gt;
&lt;div className=&quot;flex flex-col justify-center items-center&quot;&gt;
&lt;form className=&quot;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&quot;&gt;
&lt;h1 className=&quot;text-center text-green-700 text-2xl mb-4&quot;&gt;Account&lt;/h1&gt;
&lt;input className=&quot;border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700&quot; type=&quot;text&quot; placeholder=&quot;First Name&quot; name=&#39;first_name&#39; onChange={handleFormChange}/&gt;
&lt;input className=&quot;border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700&quot; type=&quot;text&quot; placeholder=&quot;Last Name&quot; name=&#39;last_name&#39; onChange={handleFormChange}/&gt;
&lt;input className=&quot;border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700&quot; type=&quot;email&quot; placeholder=&quot;Email&quot; name=&#39;email&#39; onChange={handleFormChange}/&gt;
&lt;input className=&quot;border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700&quot; type=&quot;text&quot; placeholder=&quot;Phone&quot; name=&#39;phone&#39; onChange={handleFormChange}/&gt;
&lt;input className=&quot;border-b-2 border-gray-400 w-4/5 p-2 mb-4 focus:outline-none focus:border-green-700&quot; type=&quot;password&quot; placeholder=&quot;Password&quot; name=&#39;password&#39; onChange={handleFormChange}/&gt;
&lt;button className=&quot;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&quot; type=&quot;button&quot; onClick={handleSubmit}&gt;Register&lt;/button&gt;
&lt;span&gt;Already have an account? &lt;Link to=&#39;/&#39;&gt;Login&lt;/Link&gt;&lt;/span&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
)
}
export default Account;
http-common.js
import axios from &quot;axios&quot;;
export default axios.create({
baseURL: &quot;http://localhost:5000/api&quot;,
headers: {
&quot;Content-type&quot;: &quot;application/json&quot;
}
});
server.js
const express = require(&quot;express&quot;);
const bodyParser = require(&quot;body-parser&quot;);
const cors = require(&quot;cors&quot;);
const cookie = require(&#39;cookie-parser&#39;);
require(&#39;./config/db.config&#39;);
const auth = require(&#39;./routes/route_auth&#39;);
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(&#39;/api/user&#39;, auth);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () =&gt; {
console.log(`Server is running on ${PORT}`);
});
route_auth.js
const express = require(&quot;express&quot;);
const router = express.Router();
const user = require(&quot;../controllers/auth&quot;);
router.post(&#39;/&#39;, user.register);
module.exports = router;
auth.js // controller
const user = require(&quot;../models/user&quot;);
const utils = require(&quot;../utils&quot;);
exports.register = async(req, res) =&gt; {
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) =&gt; {
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) =&gt; {
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(&#39;mongoose&#39;);
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(&quot;user&quot;, user);
db.config.js
const mongoose = require(&quot;mongoose&quot;);
const uri = &quot;mongodb://127.0.0.1:27017/employees_db&quot;
// Allow Promises
mongoose.Promise = global.Promise;
// Connection
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology:true  });
// Validation
mongoose.connection
.once(&#39;open&#39;, () =&gt; console.log(&#39;Connected to the database!&#39;))
.on(&#39;error&#39;, err =&gt; console.log(&#39;Error with the database!&#39;, err));
utils.js
const bycrypt = require(&#39;bcrypt&#39;);
// Hash Method
const hashPassword = (password, rounds) =&gt; {
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 &quot;http://localhost:5000/api/user 404 (Not Found)&quot;
</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(&#39;/api/user&#39;, auth);
// routes/route_auth.js
router.post(&#39;/&#39;, user.register);

I think your correct endpoint path is /api/user/ <- add trailing slash

huangapple
  • 本文由 发表于 2023年6月12日 08:24:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定