0

Sorry if I didnt provide the code properly

I am installing and trying to connect mongoDB, but this error comes out

     errno: -4078, code: 'ECONNREFUSED', syscall: 'connect', address: '::1', port: 27017 }, [Symbol(errorLabels)]: Set(1) { 'ResetPool' }}, topologyVersion: null, setName: null, setVersion: null, electionId: null, logicalSessionTimeoutMinutes: null, primary: null, me: null, '$clusterTime': null }

and I cant figure out, how to do as it was my first time

Here I have created two folder named frontend and backend.

enter image description here

FRONTEND CODE

`import React, { useState } from 'react';

function App() {
const \[formData, setFormData\] = useState({
name: '',
email: '',
message: ''
});

const handleInputChange = (event) =\> {
const { name, value } = event.target;
setFormData({ ...formData, \[name\]: value });
};

const handleSubmit = async (event) =\> {
event.preventDefault();

    try {
      const response = await fetch('/submit-form', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
      });
    
      if (response.ok) {
        alert('Form submitted successfully!');
        setFormData({
          name: '',
          email: '',
          message: ''
        });
      } else {
        throw new Error('Form submission failed.');
      }
    } catch (error) {
      console.error('Error:', error);
      alert('Form submission failed.');
    }

};

return (
\<div\>

<h1>Form</h1>
\
\
Name:
\<input
            type="text"
            name="name"
            value={formData.name}
            onChange={handleInputChange}
          /\>
\
<br />
\
Email:
\<input
            type="email"
            name="email"
            value={formData.email}
            onChange={handleInputChange}
          /\>
\
<br />
\
Message:
\<textarea
            name="message"
            value={formData.message}
            onChange={handleInputChange}
          \>\
\
<br />
\Submit\
\
\
);
}

export default App;

BACKEND CODE

const express = require('express'); const { MongoClient } = require('mongodb');

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

app.use(express.urlencoded({ extended: true })); app.use(express.json());

const mongoURL = 'mongodb://localhost:27017'; const dbName = 'formDB';

MongoClient.connect(mongoURL, (err, client) => { if (err) { console.error('Failed to connect to the database:', err); return; }

console.log('Connected to MongoDB!'); const db = client.db(dbName);

// Define routes and form handling logic here

// Handle form submission app.post('/submit-form', (req, res) => { const formData = req.body;

// Save form data to MongoDB
const collection = db.collection('forms');
collection.insertOne(formData, (err, result) => {
  if (err) {
    console.error('Failed to save form data:', err);
    res.status(500).send('Internal Server Error');
    return;
  }

  console.log('Form data saved:', result);
  res.status(200).send('Form submitted successfully!');
});

});

app.listen(port, () => { 
    console.log(Server is running on http://localhost:${port}); 
})

So, my problem here is that, I am unable to connect mongoDB using the above backend code, it is throwing error. I am very thankful for the help.

  • Does this answer your question? [\[Error: failed to connect to \[localhost:27017\]\] from NodeJS to mongodb](https://stackoverflow.com/questions/24710490/error-failed-to-connect-to-localhost27017-from-nodejs-to-mongodb) – rickhg12hs May 23 '23 at 21:41
  • Does this answer your question? [Can't connect to MongoDB 6.0 Server locally using Nodejs driver](https://stackoverflow.com/questions/74609210/cant-connect-to-mongodb-6-0-server-locally-using-nodejs-driver) – Wernfried Domscheit May 24 '23 at 05:42

1 Answers1

0

In your error message it seems like your backend is trying to join a MongoDB with Ipv6 address: '::1' try to use 127.0.0.1 if your MongoDB server is on the same machine and verify your /etc/hosts to be sure routing is good

Porzio Jonathan
  • 536
  • 2
  • 13
  • You don't need any `/etc/hosts` when you use an IP address. The file is used when you like to resolve an alias to according IP address. "be sure routing is good" is also pointless when you connect to localhost. – Wernfried Domscheit May 24 '23 at 06:03
  • I figured out, and its get connected. Thanks for your response.... – Swastik Kasera May 24 '23 at 06:38