This is the app.js. Here the api end point is http://localhost:3001/api/male/users/signup. Here I use mongoose, express to design the backend.
const express = require("express");
const app = express();
const morgan = require("morgan");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const maleproductRoutes = require('./api/routes/male/products');
const maleorderRoutes = require('./api/routes/male/orders');
const maleauthRoutes = require('./api/routes/male/users');
const femaleproductRoutes = require('./api/routes/female/products');
const femaleorderRoutes = require('./api/routes/female/orders');
const femaleauthRoutes = require('./api/routes/female/users');
mongoose.connect('mongodb+srv://'+process.env.MONGO_ATLAS_USER+':'+process.env.MONGO_ATLAS_PW+'@clusteretailor.extk1.mongodb.net/'+process.env.MONGO_ATLAS_DB+'?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true});
mongoose.set('useCreateIndex', true);
mongoose.Promise = global.Promise;
app.use(morgan("dev"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
// res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
return res.status(200).json({});
}
next();
});
// Routes which should handle requests
app.use('/api/male/products', maleproductRoutes);
app.use('/api/male/orders', maleorderRoutes);
app.use('/api/male/users', maleauthRoutes);
app.use('/api/female/products', femaleproductRoutes);
app.use('/api/female/orders', femaleorderRoutes);
app.use('/api/female/users', femaleauthRoutes);
app.use((req, res, next) => {
const error = new Error("Not found");
error.status = 404;
next(error);
});
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
});
});
module.exports = app;
This is the signup controller of the endpoint. I generate the JWT here and send response in body. But I don't mention anything regarding the submit data. I have no idea why the response contains the user submitted data which is unnecessary.
[const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const User = require("../../models/male/user");
router.post("/signup", (req, response, next) => {
console.log(req.body);
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length >= 1) {
return response.status(409).json({
message: "Mail exists"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return response.status(500).json({
error: err
});
} else {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash
});
user
.save()
.then(result => {
const token = jwt.sign(
{
email: result.email,
userId: result._id
},
process.env.JWT_KEY,
{
expiresIn: "1h"
}
);
return response.status(201).json({
message: "Auth successful",
token: token
});
})
.catch(err => {
console.log(err);
response.status(500).json({
error: err
});
});
}
});
}
});
});
router.post("/login", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length < 1) {
return res.status(401).json({
message: "Auth failed"
});
}
bcrypt.compare(req.body.password, user[0].password, (err, result) => {
if (err) {
return res.status(401).json({
message: "Auth failed"
});
}
if (result) {
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id
},
process.env.JWT_KEY,
{
expiresIn: "1h"
}
);
return res.status(200).json({
message: "Auth successful",
token: token
});
}
res.status(401).json({
message: "Auth failed"
});
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
router.delete("/:userId", (req, res, next) => {
User.remove({ _id: req.params.userId })
.exec()
.then(result => {
res.status(200).json({
message: "User deleted"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
// get all male users
router.get("/", (req, res, next) => {
User.find()
.exec()
.then(docs => {
console.log(docs);
// if (docs.length >= 0) {
res.status(200).json(docs);
// } else {
// res.status(404).json({
// message: 'No entries found'
// });
// }
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
module.exports = router;
when I console.log response of the api in frontend it shows config.data as below. which is unnecessary. Only what I need is data object, not config.data.
data: "{"email":"[email protected]","password":"dasdfdsvcsdv","gender":"male"}"