Hej people
I try to create some fullstack app (base on one tutorial) and I have some problem with understand how backed part work. Teoreticlly, then I did this tutorial first time, everything was working. But now, then I try to something new base on it, I see how many things I don't understand. Basically, why it won't work.
I generate express app. My app.js looks that:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var cors = require('cors');
mongoose.connect('mongodb://localhost/covid', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}).then(() => console.log('connection successful'))
.catch((err) => console.error(err));
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var casesRouter = require('./routes/cases');
var app = express();
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api', casesRouter);
module.exports = app;
routers/cases.js:
var express = require('express');
var router = express.Router();
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var Cases = require('../models/Cases.js');
server.listen(4000)
// socket io
io.on('connection', function (socket) {
socket.on('newdata', function (data) {
io.emit('new-data', { data: data });
});
socket.on('updatedata', function (data) {
io.emit('update-data', { data: data });
});
});
// list data
router.get('/', function(req, res) {
Cases.find(function (err, cases) {
if (err) return next(err);
res.json(cases);
});
})
module.exports = router;
and schema:
var mongoose = require('mongoose');
var CasesSchema = new mongoose.Schema({
id: String,
name: String,
location: String,
state: String,
});
module.exports = mongoose.model('Cases', CasesSchema);
ok, it's all.
So now I run it from my console by nodemon. In console everything looks ok. No error, and message that everything is ok. But app is not working:
1) I expect that this part:
mongoose.connect('mongodb://localhost/covid', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}).then(() => console.log('connection successful'))
.catch((err) => console.error(err));
should created me now new schema "covid" with object Cases with keys id, name, location, state. It didn't happen. I installed Compass to easiest examination my mongodb and I can see, that I don't have something like covid. ok, I created it manually, But, as I understand, it should be done automaticlly after I run nodemon.
2) I expect that I can examination my backend via postman. https://localhost:3000/api/ (3000 - nodemon default port), but I
Could not get any response There was an error connecting to
https://localhost:3000/api/.
and it's everything. I can't see this error neither in console nor postman.
Maybe I don't understand something with ports in express app, or I don't understand something with mongoDB. But google didn't help me. It did only bigger mess in my head. So maybe someone of you can explain me how it should work and why?
Related
Whenever I make a post request, it shows that message is not a constructor. Here message is a model that I made using mongoose.
And I am exporting this model through
module.exports = message and using this exported model in form_post.js file
my app.js file
const express = require('express');
const app = express();
const path = require("path");
const mongoose = require('mongoose');
const port = 3000;
const form_display = require('./routes/form_display');
const form_post = require('./routes/form_post');
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
//Backend Connection
mongoose.connect("mongodb://127.0.0.1:27017/sudeepkart", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var db = mongoose.connection;
db.once("open", function () {
console.log("We are Connected !!");
});
// Pug Specific
app.set('view engine', 'pug') //Setting View Engine as Pug
app.set('views', path.join(__dirname, 'views')) //Setting views directory so that pug files can be fetched from he views directory
// Express Specific
app.use(form_display);
app.use(form_post);
app.use('/static',express.static('static'))
app.use((req, res, next)=>{res.status(404).send('<h2>Error Page Not found</h2>')});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
})
my form_post.js file
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Message = require('../models/message.model')
const port = 3000;
router.use(express.urlencoded({ extended: false }))
router.use(express.json())
router.post('/message', function (req, res) {
// Creating New Object
var newMsg = new Message(req.body);
newMsg.save(function (err, msg) {
});
res.send('Your message has been successfully submitted');
})
module.exports = router;
my models/message.model.js file
const mongoose = require('mongoose');
// New Schema and New Model
var message_schema = new mongoose.Schema({ "id":String, "message":String });
var message = new mongoose.model("message_model", message_schema); // in other words model is a synonym for collection
module.exports = message;
Try destructuring it:
const {message} = require('../models/message.models')
MDN Documentation for destructuring
To answer your comment question, because you're trying to import Message while only exporting message. On your module.exports, I would reccomend always doing module.exports = {variable1, function2} etc, so you can destructure it and you can easily debug any issues (and stop confusion with variables too!)
I'm hoping you can help me out here because after trying over a dozen s/o solutions and reading the express docs several times, I'm stumped. I'm building a Node app that will (in the end) accept a POST from the front end app, persist it to Mongo then allow back end users to manipulate the data. I am just getting going, trying to get the POST route working and have this so far:
app.js:
const express = require("express");
const cors = require("cors");
const mongoose = require('mongoose');
const AppData = require("./model/AppData");
const uri = "mongodb://localhost:27017/lunch"
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
const router = require("./routes/index");
const PORT = 3005;
const app = express();
app.use(cors());
app.use("/", router);
app.use(express.raw({type: "application/json"}));
app.use(express.json({strict: false}));
connection.once('open', () => {
console.log('👍Successfully connected to MongoDB👍');
});
app.listen(PORT, function () {
console.log(`🚀The Backend Server is up and running on port ${PORT}🚀`);
});
index.js (routes...plan on changing the name)
const express = require('express');
const router = express.Router();
const appDataController = require('../controllers/appDataController');
router.post('/submit', appDataController.createAppData);
module.exports = router;
and appDataController.js:
const mongoose = require('mongoose');
const AppData = mongoose.model('AppData');
exports.createAppData = (req, res) => {
let reqData = req.body;
console.log(reqData);
res.send(reqData);
}
Simple enough, really, but when I grab Postman and set up a request using body/raw/json and send
{
"name": "John",
"age": "21"
}
I always see that body is undefined. From everything I've seen, I'm not doing anything wrong, but the result clearly indicates otherwise...What is it that I've missed?
Its because your using your express.json middleware after the routes, change this:
const express = require("express");
const cors = require("cors");
const mongoose = require('mongoose');
const AppData = require("./model/AppData");
const uri = "mongodb://localhost:27017/lunch"
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
const router = require("./routes/index");
const PORT = 3005;
const app = express();
app.use(cors());
app.use(express.raw({type: "application/json"}));
app.use(express.json({strict: false}));
app.use("/", router); // this need to be here
connection.once('open', () => {
console.log('👍Successfully connected to MongoDB👍');
});
app.listen(PORT, function () {
console.log(`🚀The Backend Server is up and running on port ${PORT}🚀`);
});
first comes the middlewares and then the routes(depends on the middleware your using ofcurse).
You should also include urlencoded option to get the body on x-www-form-urlencoded body for POST requests.
const app = express();
app.use(cors());
app.use(express.raw({type: "application/json"}));
app.use(express.json({strict: false}));
app.use(express.urlencoded({extended: false})); // include this line
app.use("/", router);
i'm trying to build a simple rest api based on node.js + mongodb
i'm using https://cloud.mongodb.com/ and my connection string is 1000% correct
i keep having this problem sometimes it work for me all the day no issue
and sometimes it doesn't wanna connect and i changed nothing in the code
anyone is having similar issues?
const mongoose = require('mongoose');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
// Import routes
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
//mongodb connect
mongoose.connect(process.env.db_access, { useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log('connected');
}
);
//ROUTES
app.get('/', (req,res) => {
res.send('home boi');
});
//listening port
app.listen(3000);
I've started learning on MEAN development. I had setup my express server and also my mongodb connection. On running node server in terminal the server starts running and also the mongo was able to connect but the localhost:8081/api/videos is not loading. I cleared cache and cookies but still no solution. I am attaching the code below.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const api = require('./server/routes/api');
// Port for express server
const port = 8081;
const app = express();
app.use(express.static(path.join(__dirname,'dist/mean')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json);
app.use('/api', api);
app.get('*', (req,res)=> {
res.sendFile(path.join(__dirname, 'dist/mean/index.html'));
});
app.listen(port, function(){
console.log('Server running at localhost:' + port);
});
api.js
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Video = require('../models/video');
// Creating mongo db connection
const db = 'mongodb+srv://<username>:<password>#training-qfjgb.mongodb.net/test?retryWrites=true&w=majority';
mongoose.Promise = global.Promise;
mongoose.connect(db, { useUnifiedTopology: true, useNewUrlParser: true }, err => {
if(err) {
console.log('Error: '+err);
}
else {
console.log('Successfully connected to mongodb');
}
});
router.get('/videos', function(req, res){
console.log('Get request for all videos');
Video.find({}).exec(function(err, videos){
if(err)
{console.log('Error retrieving videos');}
else
{res.json(videos);}
});
});
module.exports = router;
video.js (This is for the schema)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Creating database schema
const videoSchema = new Schema({
title: String,
url: String,
description: String
});
// Creating model of database videoplayer as model and then exporting
module.exports = mongoose.model('video', videoSchema, 'videoplayer');
const db = 'mongodb+srv://username:password#training-qfjgb.mongodb.net/test?retryWrites=true&w=majority';
username:password should be changed.
admin:12345(as you using)
const db = 'mongodb+srv://username:password#training-qfjgb.mongodb.net/test?retryWrites=true&w=majority';
Check this part thoroughly , Whether the collection name, format of the text are given correctly
Smarter programmers, please advise:
two variables coming in from an AJAX post (username, pic)
get them at the route users.js from req.body
have my functions in a file main.Funcs exported to server.js
I can't figure out how to get the variables out of my route and into my server.js, so that I can use them with my functions. Can't figure out how to do it without circular 'require' between routes and mainFuncs.
QUESTIONS:
How do you access variables from routes without (1) making global variables, nor (2) circular require between routes and mainFuncs?
Could set global variables but bad? Some way to call them in a big function that gives access to scope without making global?
server.js
var express = require('express');
var mainFuncs = require('./mainFunctions.js');
mainFuncs.startServer();
mainFuncs.sqlConnectionCheck();
mainFuncs.learnFace(username, picLink);
mainFuncs.js
const client = some api methods, input from route --> api --> json back
var express = require('express');
var users = require('./routes/users');
var bodyParser = require('body-parser');
app.use('/users', users);
var app = express();
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.use(express.static('public'));
app.use('/', main);
app.use('/users', users);
app.use('/profile', profile);
var mainFuncs = {
startServer: function () {
app.listen(3000, function() {
models.users.sync({ force: true });
models.userPicData.sync({ force: true });
console.log('Listening on port 3000!');
});
},
sqlConnectionCheck: function (){
sequelize
.authenticate()
.then(function(err) {
console.log('Connection to mysql: success.');
})
.catch(function (err) {
console.log('Connection to mysql: failed with these errors: ', err);
});
},
learnFace: function (username, picPath) {
client.faces.detect({ urls: picPath, attributes: 'all' })
.then(function(result){
var newLearn = JSON.parse(result);
var newTid = newLearn.photos[0].tags[0].tid;
var fullNameSpace = username + '#notARealNameSpace';
console.log('You have been registered with the name: ' + username);
client.tags.save(newTid, fullNameSpace, {label: nameString, password: 'optionalPassword'});
client.faces.train(nameString, { namespace: 'urface' });
})
},
};
module.exports = mainFuncs;
routes/users.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var app = express();
router.post('/create', function(req,res){
var username = req.body.username;
var picLink = req.body.pic;
});
module.exports = router;
Typically express apps are structured so that the Business Logic, Routes and Express server are in separate locations. The actual logic to your app goes inside a directory /lib. Your routes go inside /routes and your server.js goes into your project root.
/<root>
/lib
/public
/routes
server.js
package.json
Do you mean my mainFuncs should be imported into the router? It just seems like I'm writing most of the program in the routes at that point?
No, your logic goes into separate files inside /lib and your /routes will require it when necessary. This approach is decoupled and allows your logic to live outside of your routes. The logic may be implemented in multiple routes if necessary yet be centralized and easy to maintain. This leaves your routes free to only implement the code needed to determine the response and update session state.
The above code could be structured as so:
server.js
const express = require('express');
const bodyParser = require('body-parser');
const users = require('./routes/users');
// Place DB and any other initialization here in server.js
// so it will be guaranteed to execute prior to the server listening
const app = express();
const port = process.env.PORT || 1337;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static('public'));
app.use('/users', users);
app.listen(port, () => {
console.log(`Listening on ${port}`);
});
module.exports = app;
/lib/learnFace.js
const client = require('<package>'); // Some package etc per your question
function learnFace(username, picPath) {
return client.faces.detect({ urls: picPath, attributes: 'all' })
.then(function(result){
let newLearn = JSON.parse(result);
let newTid = newLearn.photos[0].tags[0].tid;
let fullNameSpace = username + '#notARealNameSpace';
console.log('You have been registered with the name: ' + username);
client.tags.save(newTid, fullNameSpace, {label: nameString, password: 'optionalPassword'});
client.faces.train(nameString, { namespace: 'urface' });
});
}
module.exports = learnFace;
/routes/users.js
const router = require('express').Router();
const learnFace = require('../lib/learnFace');
router.post('/create', (req, res) => {
let username = req.body.username;
let picLink = req.body.pic;
return learnFace(username, picLink)
.then(() => {
return res.sendStatus(201);
})
.catch((err) => {
return res.sendStatus(500);
})
});
module.exports = router;
Also you don't need to require Express in every file like you are no need to, only require the things you need in files that you are using.