[英]Storing Data into MongoDB is failing
I am new to the MERN stack and I want to store user information into the MongoDB which has two string attributes "name" and "role".我是 MERN 堆栈的新手,我想将用户信息存储到具有两个字符串属性“名称”和“角色”的 MongoDB 中。
I am getting an error in the browser console which states " Failed to load resource: Request timeout " and " Unhandled Promise Rejection: AxiosError: timeout exceeded "我在浏览器控制台中收到一条错误消息,指出“无法加载资源:请求超时”和“未处理的 Promise 拒绝:AxiosError:超时”
server index.js服务器索引.js
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
app = express();
const bookModel = require("./models/book");
const userModel = require("./models/user");
app.use(express.json());
app.use(cors);
// mongoose.connect('mongodb://mh_user:<credentials>').then(() => {console.log('test')});
mongoose.connect("mongodb://mh_user:<credentials>", {
useNewUrlParser: true,
})
// usermodel
app.postUser("/insert", async (req, res) => {
const userName = req.body.userName
const role = req.body.role
const user = new userModel({ username: userName, role: role })
try {
await userModel.save();
} catch (err) {
console.log(err);
}
});
app.getUser("/read", async (req, res) => {
userModel.find({}, (err, result) => {
if(err) {
res.send(err)
}
res.send(result)
})
});
// bookmodel
app.post("/insert", async (req, res) => {
const bookName = req.body.bookName
const ISBN = req.body.ISBN
const book = new bookModel({ bookname: bookName, ISBN: ISBN })
try {
await bookModel.save();
} catch (err) {
console.log(err);
}
});
app.get("/read", async (req, res) => {
bookModel.find({}, (err, result) => {
if(err) {
res.send(err)
}
res.send(result)
})
});
app.listen(3001, () => {
console.log("Server running on port 3001 ...");
})
client adduser.js客户端adduser.js
import styles from './Home.module.css'
import React, { useState } from "react";
import Axios from "axios"
export default function AddUser() {
const [userName, setUserName] = useState("");
const [role, setRole] = useState("");
const addToDatabase = () => {
Axios.post("http://localhost:3001/insert", { userName: userName, role: role })
}
return (
<div className={styles.container}>
<main className={styles.main}>
<h1 className={styles.title}>
Fügen Sie einen <a>neuen Nutzer</a> hinzu
</h1>
<p className={styles.description}>
Create - Operation{' '}
</p>
<div className={styles.grid}>
<form className={styles.table}>
<label>
<input
onChange={(event) => {
setUserName(event.target.value);
}}
type="name" placeholder='name'
/>
</label>
<label>
<input
onChange={(event) => {
setRole(event.target.value);
}}
type="role" placeholder='role'
/>
</label>
</form>
</div>
<br></br>
<button
onClick={addToDatabase}
>speichern</button>
<br></br>
<a href="http://localhost:3000/">
<button>Hauptmenü</button>
</a>
</main>
<footer className={styles.footer}>
<a>
Powered by{' '}- Gruppe 1
</a>
</footer>
</div>
);
}
server user.js服务器用户.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
role: {
type: String,
required: true,
}
});
const user = mongoose.model('userData', userSchema)
module.exports = user
There are many mistakes in your code:您的代码中有很多错误:
server index.js服务器索引.js
app.use(cors)
Replace it by:替换为:
app.use(cors())
Also还
app =express()
Replace it by替换为
const app= express();
Also还
app.postUser and app.getUser is not available on express middleware.
app.use and app.post are the ones.
The problem is that your app is trying to load a library called Axios and is not finding it.问题是您的应用正在尝试加载名为Axios的库,但未找到它。
Make sure Axios library is installed in your app / package.json / dependencies and been called inside your project.确保Axios库已安装在您的应用程序/package.json/依赖项中,并在您的项目中被调用。
Make sure the version of the Axios library you are using works with the node.js and express versions you are implementing.确保您使用的Axios库的版本适用于您正在实施的 node.js 和 express 版本。
Handle the exception property.处理异常属性。 Seems is not been handle the right way.似乎没有得到正确的处理方式。
Try inserting data manually from postman using you /insert endpoint.尝试使用 /insert 端点从 postman 手动插入数据。 It will help to know if database connection is working property.这将有助于了解数据库连接是否正常工作。 If so, then the issue is with the library.如果是这样,那么问题出在图书馆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.