MERN项目中Express.js应用连接MongoDB数据库遇阻求助
Express.js + Mongoose 数据库连接与交互故障排查
开发Express.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' }); } });
前端CreateBook.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;
相关截图
代码层级

前端视图

网络请求详情

网络请求头详情

前端命令行输出

后端命令行输出

内容的提问来源于stack exchange,提问作者Manoj Priyamantha
相关产品推荐
相关产品推荐

