app.post请求无法正常工作,并给我错误

时间:2019-04-23 12:05:29

标签: javascript node.js json mongodb postman

我正在尝试为我的网站构建服务器端后端代码。 我在邮递员中尝试了app.get请求,但它有效,但是当我尝试 app.post在邮递员中的请求无效,并给了我错误。

我尝试了所有在线可用的解决方案,并且我可以理解(我是Ubuntu用户)。

我在邮递员中收到的

错误屏幕截图

The following image will show you the error and format I used in postman

Server.js文件(主服务器文件)

const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");

const app = express();
const mongoose = require("mongoose");
require("dotenv").config();

mongoose.Promise = global.Promise;
mongoose
  .connect(process.env.DATABASE, { useNewUrlParser: true })
  .then(() => console.log("MongoDB Connected"))
  .catch(err => console.log(err));

// // DB config
mongoose.set("useCreateIndex", true);

// const db = require("./config/keys").mongoURI;

// Connect to MongoDB

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

// Models
const { User } = require("./models/user");

//====================================================
//                      USERS
//====================================================

app.post("/api/users/register", (req, res) => {
  const user = new User(req.body);

  user.save((err, doc) => {
    if (err) return res.json({ success: false, err });
    res.status(200).json({ success: true, userdata: doc });
  });
});

app.get("/", (req, res) => res.send("hello world"));

const port = process.env.PORT || 3002;

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

用户模型文件(models / user.js)

const mongoose = require("mongoose");

const userSchema = mongoose.Schema({
  email: {
    type: String,
    requrired: true,
    trim: true,
    unique: 1
  },
  password: {
    type: String,
    requrired: true,
    minlength: 5
  },
  name: {
    type: String,
    requrired: true,
    maxlength: 100
  },
  lastname: {
    type: String,
    requrired: true,
    maxlength: 100
  },
  cart: {
    type: Array,
    default: []
  },
  history: {
    type: Array,
    default: []
  },
  role: {
    type: Number,
    default: 0
  },
  token: {
    type: String
  }
});

const User = mongoose.model("User", userSchema);

module.exports = { User };

3 个答案:

答案 0 :(得分:0)

邮递员请求应如下所示。

{
   "email": "rohit***@gmail.com",
   "password": "password@123",
   "name": "sher",
   "lastname": "lock"
}

答案 1 :(得分:0)

您正在发送无效的JSON。

使用此JSON发送请求。

 {
      "email":"rohan3131313@gmail.com",
      "password":"password@123",
      "name":"sher",
      "lastname:"lock"
 }

答案 2 :(得分:0)

通过传递,该传递具有来自邮递员的原始数据,然后调用邮政api

{
   "email": "rohan@getMaxListeners.com",
   "password":"pass@123",
   "name":"sher",
   "lastname":"lock"
}