连接到 Mongodb atlas 时出现 500 内部服务器错误

问题描述 投票:0回答:0

我正在尝试在 mongodb atlas 上发布数据以在 db 上存储数据,但是在 mongodb atlas 上发布数据时出现 500 内部服务器错误,并且数据没有发布数据。请帮我解决这个问题。

server.js

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();

const app = express();
const port = 5000;

// connect to MongoDB
mongoose.connect(process.env.DATABASE,{
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => console.log('DB Connected'));

// import the Candidate model
const Candidate = require('./candidate');

// use middleware
app.use(bodyParser.json());
app.use(cors());

// create a route for adding a candidate
app.post('/api/addcandidate', async (req, res) => {
  const { candidate_name, party_name, imageURL } = req.body;
  try {
    const candidate = new Candidate({
      candidate_name,
      party_name,
      imageURL
    });
    await candidate.save();
    res.status(201).json({ message: 'Candidate added successfully' });
  } catch (error) {
    res.status(500).json({ message: 'Failed to add candidate' });
  }
});

app.get('/api/candidates', async (req, res) => {
  try {
    const candidates = await Candidate.find();
    res.status(200).json(candidates);
  } catch (error) {
    res.status(500).json({ message: 'Failed to get candidates' });
  }
});


// start the server
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

.env 文件

PORT=5000
DATABASE=mongodb+srv://<my userid>:< my password>@cluster0.sowg7r8.mongodb.net/?retryWrites=true&w=majority
TOKEN_SECRET=Secret

错误

POST http://localhost:5000/api/addcandidate 500 (Internal Server Error)
node.js mongodb mongodb-atlas internal-server-error
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.