Having trouble saving to mongoDB using node - node.js

I'm attempting to save data from an API response and keep getting an empty object. I placed a console.log in my code and it shows that I'm getting a response from the api. I seem to be missing something after the fetch request.
From index.js:
const express = require('express')
const bodyParser = require('body-parser')
const path = require('path')
const fetch = require('node-fetch')
const exphbs = require('express-handlebars')
const db = require('./src/models/movie')
require('./src/db/mongoose')
const Movie = require('./src/models/movie')
const app = express()
const port = process.env.PORT || 3000
// APP CONFIG
app.use(express.json())
app.use(bodyParser.urlencoded({extended: true}))
// ROUTES - ADD
app.post('/movies/:imdbID', (req, res) => {
const imdb = req.params.imdbID
const url = `**api link and key**${imdb}`
const movie = fetch(url).then((res) => {
return res.json()
}).then((response) => {
console.log(response)
const addMovie = new Movie(response)
db.Movie.create(addMovie, (err, newMovie) => {
if(err){
res.render('movie404')
} else {
res.redirect('/')
}
})
}).catch((e) => {
res.status(500).send(e)
})
})
From mongoose.js:
const mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/movietime-api', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
From details.handlebars:
<h2>{{details.Title}}</h2>
<img src="{{details.Poster}}" alt="{{details.Title}}">
<p><em>{{details.Plot}}</em></p>
<p>Starring: {{details.Actors}}</p>
<p>Director: {{details.Director}}</p>
<form action="/movies/{{details.imdbID}}" method="POST">
<button type="submit">Add</button>
</form>
From movie.js:
const mongoose = require("mongoose");
// MONGOOSE/MODEL CONFIG
const Movie = mongoose.model('Movie',{
imdbID: String,
Title: String,
Poster: String,
Director: String,
Year: String,
Plot: String,
Ratings: String,
Rated: String,
Genre: String,
Writer: String,
Actors: String
});
module.exports = Movie;
I would expect a redirect to the index page then a new database entry using the above model.

you are almost there just few thing needs to be taken care of:
app.post('/movies/:imdbID', (req, res) => {
const imdb = req.params.imdbID
const url = `**api link and key**${imdb}`
const movie = fetch(url).then((res) => {
return res.json()
}).then((response) => {
console.log(response)
const addMovie = new Movie(response)
addMovie.save((err, newMovie) => {
if(err){
res.render('movie404',newMovie) // to render the details
} else {
res.redirect('/')
}
})
}).catch((e) => {
res.status(500).send(e)
ref

Related

MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 at Timeout._onTimeout

Why am i getting this error?
I am trying to send the audio file I have on the front end using form data to the backend, where I'm using multer and gridfs to send the file to mongoDB. I have been a lot issues trying to do this with an audio file.
Why am i getting this error? I am trying to send the audio file. I have on the front end using form data to the backend where I'm using multer and gridfs to send the file to mongoDB. I have been a lot issues trying to do this with an audio file.
App.js
import React, { useState } from 'react';
function AudioUpload() {
const [file, setFile] = useState(null);
const handleFileChange = (e) => {
setFile(e.target.files[0]);
};
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('audio', file);
try {
const response = await fetch('http://localhost:4003/upload', {
method: 'POST',
body: formData,
});
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<div>
<input type="file" id="audio" name="audio" accept="audio/*" onChange={handleFileChange} />
</div>
<button type="submit" disabled={!file}>Upload</button>
</form>
</div>
);
}
export default AudioUpload;
Server.js
const express = require('express');
const mongoose = require('mongoose');
const multer = require('multer');
const Grid = require('gridfs-stream');
const { GridFsStorage } = require('multer-gridfs-storage');
const cors = require("cors");
const app = express();
app.use(cors());
const conn = mongoose.createConnection('mongodb+srv://jordandeeds31:Jd400089#cluster0.iwva5ci.mongodb.net/grid2?retryWrites=true&w=majority', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let gfs;
conn.once('open', () => {
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('audioFiles');
console.log("connected to db");
});
const storage = new GridFsStorage({
url: 'mongodb://localhost/mydatabase',
file: (req, file) => {
return {
filename: file.originalname,
bucketName: 'audioFiles',
};
},
});
const upload = multer({ storage: storage });
const audioSchema = new mongoose.Schema({
filename: { type: String, required: true },
contentType: { type: String, required: true },
fileId: { type: mongoose.Schema.Types.ObjectId, required: true },
});
const Audio = conn.model('Audio', audioSchema);
app.post('/upload', upload.single('audio'), async (req, res) => {
try {
const { originalname, mimetype } = req.file;
const fileId = req.file.id;
const audio = new Audio({
filename: originalname,
contentType: mimetype,
fileId,
});
await audio.save();
res.status(200).json({ message: 'File uploaded successfully' });
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Error uploading file' });
}
});
app.listen(4003, () => {
console.log('Server listening on port 4003');
});

Writing a database seeder class to seed multiple collections. (NodeJS, MongoDB)

Hi all I have been struggling all day with this and I was hopingsomeone might be able to assist me on figuring out the functionality. I'm still very new to asynchronous programming so any advice would be highly appreciated! I wrote two seeder classes which work great independently, and am opting to create a databaseSeeder class that I can use to run all my migrations from one file.
The issue I'm facing is that I need the UserSeeder to complete first because the ProductSeeder uses the ID's from the User model to link products to users. Please find my code for a reference:
User Seeder:
const mongoose = require("mongoose");
const User = require("../models/User");
const dotenv = require("dotenv");
const { faker } = require("#faker-js/faker");
const { v4: uuidv4 } = require("uuid");
dotenv.config();
const database = process.env.MONGOLAB_URI;
mongoose
.connect(database, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log("User Collection Connected"))
.catch((err) => console.log(err));
const seedUserList = async () => {
let users = [];
for (let i = 0; i < 5; i++) {
const userSeeder = new User({
_id: uuidv4(),
firstname: faker.name.firstName(),
lastname: faker.name.lastName(),
username: faker.internet.userName(),
email: faker.internet.email(),
contact_number: faker.phone.number("### ### ####"),
password: faker.internet.password(),
address: faker.address.streetAddress(),
avatar: faker.image.people(1920, 1080, true),
rating: 3,
isVerified: false,
isValidated: false,
});
users.push(userSeeder);
}
const seedUsers = async () => {
await User.deleteMany({});
await User.insertMany(users);
};
seedUsers().then(() => {
console.log("Users Seeded Successfully!");
mongoose.connection.close();
});
};
seedUserList();
module.exports = {
seedUserList,
};
Product Seeder:
const mongoose = require("mongoose");
const Product = require("../models/Product");
const User = require("../models/User");
const dotenv = require("dotenv");
const { faker } = require("#faker-js/faker");
const { v4: uuidv4 } = require("uuid");
dotenv.config();
const database = process.env.MONGOLAB_URI;
mongoose
.connect(database, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log("Products Collection Connected"))
.catch((err) => console.log(err));
const seedProductList = async () => {
let products = [];
let ids = [];
let idList = await User.find().select("_id");
idList.map((r) => r.toObject());
for (let i = 0; i < idList.length; i++) {
idList[i] = JSON.stringify(idList[i]);
ids.push(idList[i].substring(8, 44));
}
for (let i = 0; i < 25; i++) {
const productSeeder = new Product({
_id: uuidv4(),
name: faker.commerce.product(),
price: faker.commerce.price(),
description: faker.commerce.productDescription(),
image: faker.image.image(1920, 1080, true),
category: "Tools",
times_borrowed: faker.datatype.number(),
last_borrowed: faker.date.past(),
product_status: faker.helpers.arrayElement(["Available", "In Use"]),
user_id: faker.helpers.arrayElement(ids),
});
products.push(productSeeder);
}
const seedProducts = async () => {
await Product.deleteMany({});
await Product.insertMany(products);
};
seedProducts().then(() => {
console.log("Products Seeded Successfully!");
mongoose.connection.close();
});
};
seedProductList();
module.exports = {
seedProductList,
};
Database Seeder:
const { seedUserList } = require("./userSeeder");
const { seedProductList } = require("./productSeeder");
const mongoose = require("mongoose");
const seedDatabase = async () => {
seedUserList().then(() => {
console.log("Seeding Users!");
});
await seedProductList().then(() => {
console.log("Seeding Products!");
});
};
seedDatabase().then(() => {
console.log("Database Successfully Seeded!");
mongoose.connection.close();
});
Terminal Output
E:\Projects\Shopping-Platform>node src/seeders/databaseSeeder.js
Seeding Users!
User Collection Connected
Products Collection Connected
Seeding Products!
Database Successfully Seeded!
Products Seeded Successfully!
Users Seeded Successfully!
I've been playing around with the await functionality and wrapping each function with it's own await call so that the ProductSeeder waits for the UserSeeder to complete first before it executes, but so far no luck!

GraphQL Mongoose with MongoDB Atlas return empty array

I'm trying to connect MongoDB Atlas and mongoose but server always returns an empty array '[ ]'. When I load a mock data everything works (Mocked data and MongoDB Atlas have the same values)
I have connect to MongoDB Atlas, but can't get some data.
Controller:
const express = require('express')
const { ApolloServer } = require('apollo-server-express')
const { createServer } = require('http')
const mongoose = require('mongoose')
const typeDefs = require('./schema')
const resolvers = require('./resolvers')
const app = express()
const server = new ApolloServer({
typeDefs,
resolvers,
playground: {
endpoint: 'http://localhost:3000/graphql',
settings: {
'editor.theme': 'light'
}
}
})
server.applyMiddleware({ app })
const httpServer = createServer(app)
server.installSubscriptionHandlers(httpServer)
mongoose
.connect(`mongodb+srv://<username>:<password>#cluster0.brdqp.mongodb.net/${process.env.mongoDatabase}?retryWrites=true&w=majority`, { useNewUrlParser: true, useUnifiedTopology: true })
.then((res) => {
httpServer.listen(3000, () => {
console.log('connected!')
})
})
.catch((err) => {
console.error('Error while connecting to MongoDB', err);
})
Schema:
const { gql } = require('apollo-server-express')
const typeDefs = gql`
type Todo {
_id: String,
title: String,
description: String
status: String
date: String
}
type Query {
todos: [Todo]
}
`
module.exports = typeDefs
Resolvers:
const { Todo, Restaurant, Customer, Order } = require('./models')
const pubsub = require('./pubsub')
const resolvers = {
Query: {
todos(parent, args, context, info) {
return Todo.find()
.then(todo => {
return todo.map(r => ({ ...r._doc }))
})
.catch(err => {
console.error(err)
})
},
},
}
module.exports = resolvers
MongoDB Atlas collection: (Database name : node, collection name in DB : todo)
_id : 5c9bdb721c9d440000345d62
title : "question"
desctiption : "test test"
status: done
date: 1
But the server always returns [ ]
How???? Why&?

Not receive any data from react to nodejs

I am trying to send data from front end to back end with react and nodejs. but when I console in front end it appear data but in backend it didn't get anything.
Here is my front end code:
const [imageSelected, setImageSelected] = useState("");
// Form submission
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData();
formData.append("file", imageSelected);
const payload = { title, mission, isSearchable, userId: currentUser.id };
formData.append("payload", payload);
// Send post request for signup
const res = await axios.post("/api/v1/teams/team", formData, {
headers: { "Content-type": "multipart/form-data" },
});
// If no validation errors were found
if (res.data.validationErrors === undefined) {
// Clear any errors
setErrorsArr([]);
// Hide the errors component
setShowErrors(false);
// Toggle the modal
toggleModal();
// Go to team management page
NextRouter.push(`/team/${res.data}`);
} else {
// Set errors
setErrorsArr(res.data.validationErrors.errors);
// Show the errors component
setShowErrors(true);
}
};
<input
type="file"
className="team--modal_upload_avatar"
ref={inputFile}
onChange={(e) => setImageSelected(e.target.files[0])}
/>
<Grid item xs={12} className={classes.avatarDiv}>
<Avatar
aria-label="team"
className={classes.avatar}
component="div"
onClick={onButtonClick}
>
<AddAPhotoIcon className={classes.avatarIcon} />
</Avatar>
Here is my route:
const express = require("express");
const router = express.Router();
const { catchErrors } = require("../errors/errorHandlers");
const { body, param } = require("express-validator");
const cloudinary = require("cloudinary").v2;
const path = require("path");
const Datauri = require("datauri/parser");
const cloud_name = process.env.CLOUDINARY_NAME;
const cloud_api_key = process.env.CLOUDINARY_API_KEY;
const cloud_api_secret = process.env.CLOUDINARY_API_SECRET;
const cloud_url = process.env.CLOUDINARY_URL;
cloudinary.config({
cloud_name: cloud_name,
api_key: cloud_api_key,
api_secret: cloud_api_secret,
cloudinary_url: cloud_url,
});
// Controller
const {
createTeam,
getUsersTeams,
getManagedTeams,
getTeamCredits,
getTeamData,
updateTeamData,
shutdownTeam,
checkTeamPermissions,
checkTeamPermissionsAndLimits,
addMember,
removeMember,
addMemberBackToTeam,
quitTeam,
} = require("./teamsController");
const {
checkUserVerification,
restrictedRoute,
checkData,
} = require("../helpers/apiHelpers");
router.post(
"/team",
(req, res) => {
console.log(res);
console.log("req body", req.body);
console.log("req files", req.files);
console.log("req user", req.user);
const dUri = new Datauri();
const dataUri = (req) =>
dUri.format(path.extname(req.name).toString(), req.data);
if (req.files !== undefined && req.files !== null) {
const { file, id } = req.files;
const newFile = dataUri(file).content;
cloudinary.uploader
.upload(newFile, {
folder: "TeamAvatar",
})
.then((result) => {
const imageUrl = result.url;
const data = { id: req.body.id, imageUrl };
createTeam(data);
return res
.status(200)
.json({ message: "Success", data: { imageUrl } });
})
.catch((err) =>
res.status(400).json({ message: "Error", data: { err } })
);
} else {
return res.status(400).json({ message: "Error" });
}
},
restrictedRoute,
[
body(
"title",
"Only alphabetical characters, numbers, and spaces are allowed."
)
.not()
.isEmpty()
.isLength({ min: 1, max: 25 })
.trim()
.matches(/^[a-zA-Z0-9 ]+$/)
.blacklist("\\<\\>\\;\\[\\]\\{\\}\\|\\%\\=\\(\\)\\~\\#")
.escape(),
body("mission", "Only alphabetical characters and spaces are allowed.")
.not()
.isEmpty()
.trim()
.blacklist("\\<\\>\\;\\[\\]\\{\\}\\|\\%\\=\\(\\)\\~\\#")
.escape(),
],
checkData,
catchErrors(checkUserVerification),
catchErrors(createTeam)
);
Here is my controller that have create team function:
exports.createTeam = async (req, res) => {
// Get the user id from the session
const userId = req.session.passport.user.id;
console.log("body", req.body);
console.log("files", req.files);
console.log("file", req.file);
// Make sure user has the credits to create a new team
const teamInfo = await models.User.findOne({
where: {
id: userId,
},
attributes: ["teamCredits"],
});
if (teamInfo.dataValues.teamCredits <= 0) {
res.status(200).json({
validationErrors: {
errors: [
{
msg: "You don't have any more team credits.",
},
],
},
});
return;
}
const { title, mission } = req.body;
// const { picture } = req.imageUrl;
// Make sure the user hasn't already created a team with that title.
const existingTeam = await models.Team.findOne({
where: {
title: title,
creatorId: userId,
},
});
if (existingTeam !== null) {
// Response and let the user know.
res.status(200).json({
validationErrors: {
errors: [
{
msg: "You already created a team with that name.",
},
],
},
});
return;
}
// Generator a public team id
const firstLetter = title[0];
const secondLetter = title[1];
const thirdLetter = title[2];
const timePart = Date.now();
const generatedPublicId = `${firstLetter}${secondLetter}${thirdLetter}${timePart}`;
const roomEntry = {
name: title,
status: true,
};
const roomResponse = await models.Room.create({ ...roomEntry });
const defaultTeamValues = {
title: title,
type: "simple team",
mission: mission,
// picture: picture,
agreement: "default",
inputs: "",
outputs: "",
duration_in_months: 12,
status: "Seeking new members",
public_team_id: generatedPublicId,
mergedTo: null,
creatorId: userId,
date_closed: null,
current_members_count: 1,
current_invites_count: 0,
max_team_members_allowed: 10,
max_invites_allowed: 20,
roomID: roomResponse.dataValues.id,
};
// No existing team was found with that title and created by that user.
// Create team.
const team = await models.Team.create(defaultTeamValues);
const defaultRoleValues = {
title: "creator",
duties: "",
rights: "all",
};
// Create role for new team
const role = await models.Role.create(defaultRoleValues);
const defaultMembershipValues = {
interests: "",
contributions: "",
authorization: "creator",
status: "active",
application_letter: "",
date_applied: Sequelize.literal("CURRENT_TIMESTAMP"),
date_joined: Sequelize.literal("CURRENT_TIMESTAMP"),
date_departed: null,
memberId: userId,
teamId: team.dataValues.id,
roleId: role.dataValues.id,
};
// Create membership for team with role and team ids
await models.Membership.create(defaultMembershipValues);
const newCreditValue = teamInfo.dataValues.teamCredits - 1;
// Update team credits the user has.
await models.User.update(
{ teamCredits: newCreditValue },
{
where: {
id: userId,
},
}
);
// Done
res.status(200).json(team.dataValues.public_team_id);
};
Why my back end didn't get any data I sent from front end to back end?
Add files
server.js:
/* eslint-disable no-undef */
const express = require("express");
const next = require("next");
const dotenv = require("dotenv");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const compression = require("compression");
const bodyParser = require("body-parser");
const logger = require("morgan");
const session = require("express-session");
const SequelizeStore = require("connect-session-sequelize")(session.Store);
const passport = require("passport");
const helmet = require("helmet");
const sslRedirect = require("heroku-ssl-redirect");
const socketIo = require("socket.io");
const http = require("http");
const {
saveMessage,
getAllMessagedByRoomID,
} = require("./services/chat/chatController");
// Setup Next.js then run express.
app.prepare().then(() => {
// Setup express
const server = express();
const chatServer = http.createServer(server);
const io = socketIo(chatServer);
// Socket Connection Start
io.on("connection", (socket) => {
chatID = socket.handshake.query.chatID;
socket.join(chatID);
//Send message to only a particular user
socket.on("send_message", (message) => {
saveMessage(message);
io.in(message.roomID).emit("receive_message", {
content: message.content,
roomID: message.roomID,
userID: message.userID,
});
});
socket.on("get_all_messages", async ({ roomID }) => {
const allMessagedByRoomID = await getAllMessagedByRoomID(roomID);
io.in(roomID).emit("send_all_messages", {
allMessagedByRoomID,
});
});
});
// Redirect all traffic to use ssl(https);
server.use(sslRedirect());
// Define PORT
const port = process.env.PORT || 3000;
let serverMode = "development";
// Check if node is setup for production
if (!dev) {
serverMode = "production";
}
if (serverMode === "production") {
server.use(helmet());
}
// Logger
server.use(
logger("dev", {
skip: function (req, res) {
return res.statusCode < 199; // Only log 400 and 500 codes
},
})
);
// Use body parser
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());
// Compression
server.use(compression());
// Database
const db = require("./models/index");
const sequelize = db.sequelize;
// Test db connection
sequelize
.authenticate()
.then(() => {
console.log("Database successfully connected!");
})
.catch((err) => {
throw new Error(err);
});
// Sessions Setup
const sessionMaxTime = 1000 * 60 * 60 * 24 * 5; // 5 Days
// Session options
const theSession = {
secret: process.env.SECRET,
name: "sessId",
resave: false,
saveUninitialized: false,
cookie: {
maxAge: sessionMaxTime,
sameSite: true,
},
store: new SequelizeStore({
db: sequelize,
table: "Session",
}),
};
// Session production options
if (serverMode === "production") {
server.set("trust proxy", 1); // Trust first proxy
theSession.cookie.secure = true; // Serve cookies on HTTPS only
}
server.use(session(theSession));
// Passport Setup
// require("./config/passport")(passport);
require("./config/passport");
server.use(passport.initialize());
server.use(passport.session());
// API Routes
const userRoutes = require("./services/users/usersAPI");
server.use("/api/v1/users", userRoutes);
const profileRoutes = require("./services/profiles/profilesAPI");
server.use("/api/v1/profiles", profileRoutes);
const teamRoutes = require("./services/teams/teamsAPI");
server.use("/api/v1/teams", teamRoutes);
const searchRoutes = require("./services/searches/searchAPI");
server.use("/api/v1/search", searchRoutes);
const ratingRoutes = require("./services/ratings/ratingsAPI");
server.use("/api/v1/ratings", ratingRoutes);
const inviteRoutes = require("./services/invites/invitesAPI");
server.use("/api/v1/invites", inviteRoutes);
const feedbackRoutes = require("./services/feedback/feedbackAPI");
server.use("/api/v1/feedback", feedbackRoutes);
const couponRoutes = require("./services/coupons/couponsAPI");
server.use("/api/v1/coupons", couponRoutes);
const chatRoutes = require("./services/chat/chatAPI");
server.use("/api/v1/chat", chatRoutes);
// Restricted Pages
const restrictedRoutes = require("./services/restricted/restrictedAPI");
server.use(restrictedRoutes);
// Run server
sequelize.sync({ force: true }).then(() => {
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready in ${serverMode} mode.`);
});
});
});
To handle HTTP POST requests in Express.js version 4 and above, you need to install the middleware module called body-parser.
body-parser extracts the entire body portion of an incoming request stream and exposes it on req.body.
const express = require('express')
const app = express()
const bodyParser = require('body-parser');
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
router.post("/team", (req, res) => {...})
In Addition:
To handle multipart/form-data request that support file upload, you
need to use multer multer module.
Basic usage example:
Don't forget the enctype="multipart/form-data" in your form.
<form action="/profile" method="post" enctype="multipart/form-data">
<input type="file" name="avatar" />
</form>
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
// req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
//
// e.g.
// req.files['avatar'][0] -> File
// req.files['gallery'] -> Array
//
// req.body will contain the text fields, if there were any
})
In your case: route.js
const express = require("express");
const app = express();
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const router = express.Router();
const { catchErrors } = require("../errors/errorHandlers");
const { body, param } = require("express-validator");
const cloudinary = require("cloudinary").v2;
const path = require("path");
const Datauri = require("datauri/parser");
const cloud_name = process.env.CLOUDINARY_NAME;
const cloud_api_key = process.env.CLOUDINARY_API_KEY;
const cloud_api_secret = process.env.CLOUDINARY_API_SECRET;
const cloud_url = process.env.CLOUDINARY_URL;
cloudinary.config({
cloud_name: cloud_name,
api_key: cloud_api_key,
api_secret: cloud_api_secret,
cloudinary_url: cloud_url,
});
// Controller
const {
createTeam,
getUsersTeams,
getManagedTeams,
getTeamCredits,
getTeamData,
updateTeamData,
shutdownTeam,
checkTeamPermissions,
checkTeamPermissionsAndLimits,
addMember,
removeMember,
addMemberBackToTeam,
quitTeam,
} = require("./teamsController");
const {
checkUserVerification,
restrictedRoute,
checkData,
} = require("../helpers/apiHelpers");
router.post(
"/team", upload.single('file'),
(req, res) => {
console.log(res);
// req.file is the `file` file
// req.body will hold the text fields, if there were any
console.log("req body", req.body);
console.log("req file", req.file);
console.log("req user", req.user);
const dUri = new Datauri();
const dataUri = (req) =>
dUri.format(path.extname(req.name).toString(), req.data);
if (req.files !== undefined && req.files !== null) {
const { file, id } = req.files;
const newFile = dataUri(file).content;
cloudinary.uploader
.upload(newFile, {
folder: "TeamAvatar",
})
.then((result) => {
const imageUrl = result.url;
const data = { id: req.body.id, imageUrl };
createTeam(data);
return res
.status(200)
.json({ message: "Success", data: { imageUrl } });
})
.catch((err) =>
res.status(400).json({ message: "Error", data: { err } })
);
} else {
return res.status(400).json({ message: "Error" });
}
},
restrictedRoute,
[
body(
"title",
"Only alphabetical characters, numbers, and spaces are allowed."
)
.not()
.isEmpty()
.isLength({ min: 1, max: 25 })
.trim()
.matches(/^[a-zA-Z0-9 ]+$/)
.blacklist("\\<\\>\\;\\[\\]\\{\\}\\|\\%\\=\\(\\)\\~\\#")
.escape(),
body("mission", "Only alphabetical characters and spaces are allowed.")
.not()
.isEmpty()
.trim()
.blacklist("\\<\\>\\;\\[\\]\\{\\}\\|\\%\\=\\(\\)\\~\\#")
.escape(),
],
checkData,
catchErrors(checkUserVerification),
catchErrors(createTeam)
);

Socket hang up when using axios

I'm having an error "Error: socket hang up" and I don't know what causes this but it saves the data in database.
here's my code:
dataschema.js
const mongoose = require("mongoose");
const DataSchema = new mongoose.Schema({
data1: {
type: String
},
data2: {
type: String
},
data3: {
type: String
},
data4: {
type: String
},
});
const DataModel = mongoose.model("TEST123", DataSchema);
module.exports = DataModel;
routes.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const DataModel = require('./models/dataschema');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
mongoose.connect(
"mongodb://localhost:27017/stocksmonitor?readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false",
{ useNewUrlParser: true }
);
app.post('/insert', (req, res) => {
const stock = new DataModel({
data1: req.body[0],
data2: req.body[1],
data3: req.body[2],
data4: req.body[3],
})
stock.save();
})
app.listen(3001, () => {
console.log("You are connected");
})
savedata.js
const axios = require('axios');
SaveInfo = () => {
const testdata = ["a", "b", "c", "d"]
axios({
method: 'post',
url: 'http://localhost:3001/insert',
data: testdata
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
SaveInfo();
I inspected the code and found that you did not return response for your controller. In the code below after the save add res.send() or res.json(). So express can return a proper response. Otherwise request will timed out, because it did not resolve and Express will cut the connection. Therefore axios is throwing Error: Socket hang up unexpectedly.
app.post('/insert', (req, res) => {
const stock = new DataModel({
data1: req.body[0],
data2: req.body[1],
data3: req.body[2],
data4: req.body[3],
})
stock.save();
})

Resources