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".
I am getting an error in the browser console which states "Failed to load resource: Request timeout" and "Unhandled Promise Rejection: AxiosError: timeout exceeded"
server index.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
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
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
2
Answers
There are many mistakes in your code :
server index.js
Replace it by :
Also
Replace it by
Also
The problem is that your app is trying to load a library called Axios and is not finding it.
Make sure Axios library is installed in your app / package.json / dependencies and been called inside your project.
Make sure the version of the Axios library you are using works with the node.js and express versions you are implementing.
Handle the exception property. Seems is not been handle the right way.
Try inserting data manually from postman using you /insert endpoint. It will help to know if database connection is working property. If so, then the issue is with the library.