- 对不起,如果我没有提供正确的代码 *
我正在安装mongoDB并尝试连接,但出现此错误
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 }
我不知道该怎么做因为这是我的第一次
我在这里创建了两个文件夹,名为frontend和backend。
前端代码
`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;
后端代码
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});
})
所以,我这里的问题是,我无法使用上面的后端代码连接mongoDB,它抛出错误。我非常感谢你的帮助。
1条答案
按热度按时间efzxgjgh1#
在您的错误消息中,似乎您的后端正在尝试使用Ipv6
address: '::1'
加入MongoDB,如果您的MongoDB服务器在同一台机器上,请尝试使用127.0.0.1
,并验证您的/etc/hosts
以确保路由正常