node.js - 使用邮递员将dataSchema发送到mongodb
问题描述
我用更多信息更新了这个问题:“我对 Express/mongodb 很陌生,我正在尝试使用邮递员将我的 userSchema 发送到 mongoDb,但我收到了这个错误:”
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);
这是用户架构:
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
name: {
type: String,
maxlength: 50
},
email: {
type: String,
trim: true,
unique: 1
},
password: {
type: String,
minlength: 5
},
lastname: {
type: String,
maxlength: 50
},
role: {
type: Number,
default: 0
},
token: {
type: String
},
tokenExp: {
type: Number
}
});
const User = mongoose.model("User", userSchema);
module.exports = { User };
请问我做错了什么?
解决方案
您在 POST 方法中创建函数,但在 Postman 中您使用的是 GET 方法。请选择 POST 方法并尝试在 Postman 的 Body 中发送原始数据。
请使用以下代码来允许 body-parser 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();
});
推荐阅读
- c# - button.OnClick 监听器触发两次
- javascript - 带参数的 JavaScript addEventListener 函数
- javascript - 如何让整个应用程序全局可用的 MySQL 连接
- c++ - C++:获取参数包的头部和尾部
- bash - 动态 Make Dependencies 可能吗?
- oracle - Oracle DBMS_DEBUG.GET_VALUE 在调试大包时无法获取变量值
- zeromq - ZeroMQ 正在丢弃消息
- snowflake-cloud-data-platform - 在“预览应用”中,过滤器不会更新
- node.js - Docker swarm secret 在 node.js api (mongoDB) 中无法正常工作
- apache - .htaccess 保留字?/ URL中的“目录”