我对React Native还是很陌生,我试图弄清楚如何将前端连接到后端。我意识到我的文件夹结构可能设置得很奇怪,但是连接正常,我可以从数据库中获取数据,但是当我尝试发布时,它会引发500错误。我似乎无法弄清楚这是怎么回事。如果有人有见识,我将不胜感激。 post方法控制台将req.body和“我们在这里”记录在控制器文件中,但此后立即失败。
// index.js
require("dotenv").config();
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const morgan = require("morgan");
const { UserRoutes, TweetsRoutes } = require("./modules");
import dbConfig from "./config/db";
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan("dev"));
// -----Database ----- \\
dbConfig(process.env.MONGO_DB_URL);
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.use("/api", [UserRoutes, TweetsRoutes]);
// app.get("/", (req, res) => {
// res.send("endpoint live");
// });
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));
// db.js
const mongoose = require("mongoose");
export default mongoURL => {
mongoose.Promise = global.Promise;
mongoose.connect(
mongoURL,
{ useNewUrlParser: true }
);
let db = mongoose.connection;
db.once("open", () => console.log("Connected to the database"));
db.on("error", console.error.bind(console, "Mongo connection error: "));
};
// tweetController.js
import Tweet from "./TweetsSchema";
module.exports = {
createTweet: async (req, res, next) => {
const createdTweet = req.body;
console.log("req.body: ", req.body);
try {
console.log("Here we are");
let tweet = await new Tweet.create(createdTweet);
tweet.save();
console.log("tweet: ", tweet);
res.status(201).json(tweet);
} catch (error) {
res.status(500).json({
error: true,
message: "There was an error creating the tweet"
});
}
},
getAllTweets: async (req, res, next) => {
const foundTweets = await Tweet.find({})
.lean()
.exec();
res.status(200).json(foundTweets);
next();
}
};
// actions.js
export const postTweet = tweet => {
let response = axios
.post(
`http://10.0.2.2:<PORT>/api/tweet`,
{ tweet },
{
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*"
}
}
)
.then(res => {
return res.data;
})
.catch(error => {
console.log(error);
});
return {
type: POST_TWEET,
payload: response
};
};
答案 0 :(得分:1)
问题是您混入了两个用于创建新文档的命令
不要像这样同时使用new
和create
:
let tweet = await new Tweet.create(createdTweet);
您应该只使用其中的一种:
let tweet = await Tweet.create(createdTweet);
tweet.save();
或者:
let tweet = new Tweet(createdTweet);
await tweet.save();