如何从前端发送数据到MongoDB
这是我第一次处理数据库,我真的面临一些困难,希望有人可以帮助我。
IM试图将数据从前端(React JS)发送到后端(节点JS),然后将数据发送到MongoDB数据库(因此将其保存在那里)。我用数据成功地致电了服务器,但我无法将日期发送到服务器的数据库。这些是我的文件。
react js file :(当用户输入一些文本并单击按钮时,调用此函数)
handleSubmit = () => {
console.log("its running");
let databody = {
message: this.state.val,
};
console.log(" the message is :" + this.state.val);
return fetch("http://localhost:5000/stored", {
method: "POST",
body: databody,
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then((data) => console.log(data));
};
index.js/server文件:不知道我应该将其定义为什么,如果我以正确的方式定义数据,我的问题会被解决吗?)
const express = require("express");
const cors = require("cors"); // Importing cors
var request = require("request");
const dotenv = require("dotenv");
const port = 5000;
var request = require("request");
var util = require("util");
const connectDB = require("./config/db");
require("dotenv").config({ path: "./config/config.env" });
const app = express();
dotenv.config();
connectDB();
app.get("/", (req, res) => {
res.send("Hey there!");
});
app.get("/Pinged", function (req, res) {
find_my_iphone();
res.send("Pinged!");
});
app.use(cors({ origin: "*" }));
app.post("/stored", (req, res) => {
console.log("its running 2: " + req.body);
db.collection("quotes").insertOne(req.body, (err, data) => {
if (err) return console.log(err);
res.send("saved to db: " + data);
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
配置文件夹中的DB.JS文件:
const mongoose = require("mongoose");
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
// useCreateIndex: true,
// useFindAndModify: false,
});
console.log(`MongoDB Connected : ${conn.connection.host}`);
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
module.exports = connectDB;
谢谢。
This is my first time dealing with databases and im really facing some difficulties and hope someone can help me out.
Im trying to send data from the front-end(react js) to the back-end(node js) and then to mongodb database (so it would be saved there). I called the server succefully with the data, but Im not able to send the date to the database from the server. These are my files.
react js file: ( this function is called when the user enters some text and clicks on a button )
handleSubmit = () => {
console.log("its running");
let databody = {
message: this.state.val,
};
console.log(" the message is :" + this.state.val);
return fetch("http://localhost:5000/stored", {
method: "POST",
body: databody,
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then((data) => console.log(data));
};
index.js/server file: ( here is where im getting my error which says that db is not defined, honestly i get it but i dont know what am i supposed to define it as, and will my problem be solved the data be sent if i define it the right way?)
const express = require("express");
const cors = require("cors"); // Importing cors
var request = require("request");
const dotenv = require("dotenv");
const port = 5000;
var request = require("request");
var util = require("util");
const connectDB = require("./config/db");
require("dotenv").config({ path: "./config/config.env" });
const app = express();
dotenv.config();
connectDB();
app.get("/", (req, res) => {
res.send("Hey there!");
});
app.get("/Pinged", function (req, res) {
find_my_iphone();
res.send("Pinged!");
});
app.use(cors({ origin: "*" }));
app.post("/stored", (req, res) => {
console.log("its running 2: " + req.body);
db.collection("quotes").insertOne(req.body, (err, data) => {
if (err) return console.log(err);
res.send("saved to db: " + data);
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
db.js file inside config folder:
const mongoose = require("mongoose");
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
// useCreateIndex: true,
// useFindAndModify: false,
});
console.log(`MongoDB Connected : ${conn.connection.host}`);
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
module.exports = connectDB;
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,您在这里做错了几件事。
首先更改您的
db.js
文件,然后使其返回连接实例。将其更改为
第二个,现在您可以在
index.js/server
文件中使用DB。更改
index.js/server
文件Actually you are doing couple of things wrong here.
First change your
db.js
file and make it return the connection instance.Change it to this
Second, Now you can use the db in your
index.js/server
file.Change you
index.js/server
file to this