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);
Related
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const Observation = require("./schema/dreamWorld");
const bodyParser = require("body-parser");
const cors = require("cors");
app.get("/", (req, res) => res.send("Hello World"));
app.listen(3000, () => console.log("Server started on port 3000"));
app.use(cors, bodyParser.json());
app.get("/world", (req, res) => {
return res.status(200).json({ message: "HAppy?" });
});
const mongoDB = "mongodb://127.0.0.1/test";
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
in the above coding that I am testing in Postman! I can connect to "/" route and postman displays hello world! but when I search "/world" get route in postman it keeps on loading forever and does not fetch anything.
I have made sure server is running with correct Port number. what am I doing wrong here?
The body-parser no more necessary if use express V4.16 or later.
It is included into express.js.
More detail is explained in here.
This code will be works.
const express = require("express");
const mongoose = require("mongoose");
const Observation = require("./schema/dreamWorld");
const cors = require("cors");
const app = express();
app.use(cors())
app.get("/", (req, res) => res.send("Hello World"));
app.get("/world", (req, res) => {
return res.status(200).json({ message: "Happy?" });
});
const mongoDB = "mongodb://127.0.0.1/test";
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
app.listen(3000, () => console.log("Server started on port 3000"));
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'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
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?
I tired to solve this problem, when I browse localhost:5000 I got error like
Cannot GET /
//*****************app.js************
const express = require('express');
const mongoose = require('mongoose');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express();
const v1 = require('./routes/v1');
// ************* DB Config *************//
mongoose.connect(process.env.MONGO_DB_URL, {
useNewUrlParser: true,
useCreateIndex: true
});
mongoose.connection.on('connected' , () => {
console.log('Connected to the databse');
});
mongoose.connection.on('error' , (err) => {
console.error('Failed to connected to the databse: ${err}');
});
//**************Midlewares ***********//
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : true}));
//*************Routes *****************//
app.use('/api/v1', v1);
module.exports = app ;
//********** index.js ***************//
require('dotenv').config();
const app = require('./src/app')
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log('Server is ready for connections on port ${PORT}');
});
the problem here is you have no route at the root /
you have to add either your routes you defined or define a root route