我目前正在使用Mongoes.js应用程序,试图使用Mongoose连接到MongoDB数据库。但是,我遇到了一个数据库连接问题,需要一些帮助来解决这个问题。以下是详细信息:
我有一个js.js应用程序,我使用Mongoose连接到MongoDB数据库。我已经按照标准步骤设置了数据库连接,但在尝试与数据库交互时出现错误。
app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(cors({ origin: '*' }));
mongoose.connect('mongodb://127.0.0.1:27017/library_db', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Other routes and middleware...
app.listen(PORT, () => {
console.log(`Backend Server is running on port ${PORT}`);
});
// POST /book
app.post('/book', async (req, res) => {
try {
const { name, isbn, author } = req.body;
const book = new Book({ name, isbn, author });
await book.save();
res.status(201).json(book);
} catch (error) {
res.status(500).json({ error: 'An error occurred' });
}
});
前端电子书. js
import React, { useState } from 'react';
import axios from 'axios';
function CreateBook() {
const [name, setName] = useState('');
const [isbn, setIsbn] = useState('');
const [author, setAuthor] = useState('');
const [message, setMessage] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
const newBook = {
name,
isbn,
author,
};
axios.post('/book', newBook)
.then(response => {
setMessage('Book created successfully');
setName('');
setIsbn('');
setAuthor('');
})
.catch(error => {
console.error(error);
setMessage('An error occurred while creating the book');
});
};
return (
<div className="container mt-4">
<h2>Create Book</h2>
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label className="form-label">Name:</label>
<input type="text" className="form-control" value={name} onChange={e => setName(e.target.value)} required />
</div>
<div className="mb-3">
<label className="form-label">ISBN:</label>
<input type="text" className="form-control" value={isbn} onChange={e => setIsbn(e.target.value)} required />
</div>
<div className="mb-3">
<label className="form-label">Author:</label>
<input type="text" className="form-control" value={author} onChange={e => setAuthor(e.target.value)} required />
</div>
<button type="submit" className="btn btn-primary">Create Book</button>
</form>
<p className="mt-3">{message}</p>
</div>
);
}
export default CreateBook;
1条答案
按热度按时间ca1c2owp1#
检查您的路由和服务器端口。问题出在路上。