使用邮递员将dataSchema发送到mongodb

时间:2020-03-11 10:02:29

标签: node.js mongodb express mongoose postman

我用更多信息更新了问题:“ 我是Express / mongodb的新手,我正在尝试使用邮递员将userSchema发送到mongoDb,但出现此错误:“

postman

postman 这是我的主要脚本:

15
10
3

这是userSchema:

mongoose
  .connect(config.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log("db connected"))
  .catch(err => console.log(err));

app.use(cors());
app.options("*", cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());

app.post("/api/users/register", (req, res) => {
  const user = new User(req.body);
  user.save((err, userData) => {
    if (err) return res.json({ success: false, err });
  });
  return res.status(200);
});
app.listen(5000);

请问我做错了什么?

2 个答案:

答案 0 :(得分:1)

您使用的是POST请求,但您在邮递员中使用的是GET请求,因此最好更改为使用异步并等待,因为服务器响应可能会花费一些时间,因此请尝试

computed

答案 1 :(得分:1)

您在POST方法中创建函数,但在Postman中,您正在使用GET方法。请选择POST方法,然后尝试在Postman的正文中发送Raw数据。

请使用以下代码允许正文解析器JSON和方法。

app.use(bodyParser.json({ type: 'application/*' }));
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', "*");
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials');
  res.header('Access-Control-Allow-Credentials', 'true');
  next();
});