Мой маршрут .post, кажется, работает только при наличии ошибки, у меня есть другой маршрут .post, который прекрасно работает, и они оба написаны точно так же, поэтому я очень запутался, почему это происходит. Если я не заполняю все поля, я получаю «UnhandledPromiseRejectionWarning», как и ожидалось, то есть он пытался выполнить маршрут, но если каждое поле введено правильно, ничего не происходит вообще. Даже не работает console.log (), и он не сохраняет элемент.
Сервер
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
//Routes
const users = require("./routes/users");
const bugs = require("./routes/bugs");
const app = express();
//Bodyparser Middleware
app.use(bodyParser.json());
app.use(cors());
// DB Config
app.use("/api/users", users);
app.use("/api/bugs", bugs);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
пн goose маршрут
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const Users = require("../schemas/users_schema");
router.post("/", (req, res) => {
const newUser = new Users({
Firstname: req.body.Firstname,
Lastname: req.body.Lastname,
Email: req.body.Email,
Password: req.body.Password,
DOB: req.body.DOB
});
console.log(newUser);
newUser.save().then(item => res.json(item));
console.log("Account created");
});
топор ios запрос
export const addItem = item => dispatch => {
axios.post("/api/users", item).then(res =>
dispatch({
type: ADD_ITEM,
payload: res.data
})
);
};
HTML / JSX
<form>
<div>
<div className="signUp">
<input
type="date"
className="form-control form-control-lg"
placeholder="Enter your date of birth..."
onChange={() => this.setDOB.bind(this)}
value={this.state.DOB}
/>
<div className="sep" />
<input
type="email"
className="form-control form-control-lg"
placeholder="Enter your email..."
onChange={() => this.setEmail.bind(this)}
value={this.state.Email}
/>
<div className="sep"></div>
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter your first name..."
onChange={() => this.setFirstname.bind(this)}
value={this.state.Firstname}
/>
<div className="sep"></div>
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter your last name..."
onChange={() => this.setLastname.bind(this)}
value={this.state.Lastname}
/>
<div className="sep" />
<input
type="text"
className="form-control form-control-lg"
placeholder="Create your password..."
onChange={() => this.setPassword.bind(this)}
value={this.state.Password}
/>
<button
className="btn btn-block btn-lg btn-primary"
onClick={() => {
const newUser = {
Firstname: this.state.Firstname,
Lastname: this.state.Lastname,
Email: this.state.Email,
Password: this.state.Password,
DOB: this.state.DOB
};
this.props.addItem(newUser);
}}
>
Sign up!
</button>
</div>
<div className="sep" />
</div>
</form>
Javascript установка значений
setDOB = e => {
this.setState({ DOB: e.target.value });
};
setEmail = e => {
this.setState({ Email: e.target.value });
};
setFirstname = e => {
this.setState({ Firstname: e.target.value });
};
setLastname = e => {
this.setState({ Lastname: e.target.value });
};
setPassword = e => {
this.setState({ Password: e.target.value });
};
const mongoose = require("mongoose");
const bcrypt = require("bcrypt"),
SALT_WORK_FACTOR = 10;
const Schema = mongoose.Schema;
// Create Schema
const Users = new Schema({
Firstname: {
type: String,
required: true
},
Lastname: {
type: String,
required: true
},
Email: {
type: String,
required: true
},
Password: {
type: String,
required: true
},
DOB: {
type: Date,
required: true
},
GroupID: {
type: String,
required: false,
default: "NOGROUP"
}
});
//https://stackoverflow.com/questions/14588032/mongoose-password-hashing
Users.pre("save", function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified("Password")) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.Password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.Password = hash;
next();
});
});
});
Users.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.Password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = User = mongoose.model("Users", Users);