Cannot GET /chatroom - javascript

I am new here.
I am trying to develop a web application and I have hit a brick wall which I've been stuck on for a while now.
When running my app.js file all pages show up except for the chatroom. Could someone please take a look at the code and help me out?
I haven't included my code for register and login etc. as they are working fine. When using their router.get and .post concepts for the chatroom I just receive a "Cannot GET /chatroom" message.
Chatroom.js:
const express = require('express');
const router = express.Router();
const socketClient = require('socket.io').listen(4000).sockets;
//Chatroom page: Credit - Traversy Media - https://www.youtube.com/watch?v=hrRue5Rt6Is&t=1542s
router.get('/chatroom', (req, res) => res.render('chatroom.ejs'));
router.post('/chatroom', (req, res) => {
// Connect to Socket.io
socketClient.on('connection', function (socket) {
let chat = db.collection('UsersDB/chats');
// Create function to send status
sendStatus = function (s) {
useUnifiedTopology: true,
socket.emit('status', s);
}
// Get chats from mongo collection
chat.find().limit(100).sort({ _id: 1 }).toArray(function (err, res) {
if (err) {
throw err;
}
// Emit the messages
socket.emit('output', res);
});
// Handle input events
socket.on('input', function (data) {
let name = data.name;
let message = data.message;
// Check for name and message
if (name == '' || message == '') {
// Send error status
sendStatus('Please enter a name and message');
} else {
// Insert message
chat.insert({ name: name, message: message }, function () {
socketClient.emit('output', [data]);
// Send status object
sendStatus({
message: 'Message sent',
clear: true
});
});
}
});
// Handle clear
socket.on('clear', function (data) {
// Remove all chats from collection
chat.remove({}, function () {
// Emit cleared
socket.emit('cleared');
});
});
});
});
app.js:
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const passport = require('passport');
const flash = require('connect-flash');
const session = require('express-session');
const app = express();
// Passport Config
require('./config/passport')(passport);
// DB Config
const db = require('./config/keys').mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
// Express body parser
app.use(express.urlencoded({ extended: true }));
// Express session
app.use(
session({
secret: 'secret',
resave: true,
saveUninitialized: true
})
);
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
// Connect flash
app.use(flash());
// Global variables
app.use(function(req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
// Routes
app.use('/', require('./routes/index.js'));
app.use('/users', require('./routes/users.js'));
app.use('/chatroom', require('./routes/chatroom.js'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on port ${PORT}`));

First and foremost I'd like to thank Cranky Coder; Prakher Londe; and Sunil Lulla for your replies.
I ended up figuring out how to make the chatroom show up. As mentioned before my other pages(login and register etc.) were showing up fine. Unlike the chatroom I had the backend for these in a users.js file. So what I decided to do was move my chatroom.js code into my users.js which was then called in the app.js(the file I run) with app.use('/users', require('.routes/users.js')).
I then changed my router.get code to:
router.get('/chatroom', (req, res) => res.render('chatroom', {
user: req.user
}));
Then in my router.post (see OP for context) I added a res.redirect('/users/chatroom'); before closing with the final bracket.
Lastly I of course edited my .ejs file to have
I found that doing it this way is even better because the chatroom cannot be accessed unless one is logged in.
Thank you again for all your replies and although this is a bit of a specific problem I do hope this helps someone in the future.

Related

How do i get my mongo schema to export into a file then use it to insert data?

I am having trouble being able to insert data into my collection, I'm not even sure I'm doing it correctly so I apologize for the vague request but maybe my code will help you see what my intention is. The gist of it is I'm trying to make a separate file for my schema/collection and then call it from another file and insert data and call other functions etc.
file1.js file:
require('dotenv').config()
const User = require('./assets/js/data')
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
mongoose.connect(process.env.url, { useNewUrlParser: true })
.then(() => {
console.log('Connected to MongoDB server');
})
// 1. Import the express module
const express = require('express');
// 2. Create an instance of the express application
const app = express();
app.set('views', './static/html');
app.set('view engine', 'ejs');
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// 3. Define the HTTP request handlers
app.get('/', (req, res) => {
res.render('main')
});
app.get('/login', (req, res) => {
res.render('login')
});
app.post('/login', (req, res) => {
console.log(req.body.number);
})
app.listen(3000, (err) => {
console.log("running server on port")
if (err) {
return console.log(err);
}
})
data.js
const mongoose = require('mongoose');
const userData = new mongoose.Schema({
phoneNumber: String,
})
const User = mongoose.model('User', userData);
module.exports(
User,
)
This line has the error.
// error
module.exports(
User,
)
module.exports is not a function.
module.exports = User
// or
module.exports = { User }
if you do the first one, then required should be like this,
const User = require('./assets/js/data')
otherwise
const { User } = require('./assets/js/data')
More about module.exports
The Data.js is correct but the way your controller works is I think the issue. If you use "const User = require('./assets/js/data')" you can use your selected variable User and then connect find, create, etc. you can use this as a reference. https://blog.logrocket.com/mern-stack-tutorial/

nodejs passport callback not being called

I am very new to both JS and NodeJs/Express. I am writing a proof of concept MVP node/express app that uses passport for authentication (via social logins).
I have written the server and installed all required packages and so far everything (apart from the authentication bit works).
Note: I have already set up my credentials at the various social media company's ends, so this is not the problem.
Here is a snippet of my code:
app.js
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
compression = require('compression'),
shouldCompress = (req, res) => {
if (req.headers['x-no-compression']) {
// don't compress responses if this request header is present
return false;
}
// fallback to standard compression
return compression.filter(req, res);
};
const app = express();
// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
// Parsing related
app.use(express.urlencoded( { extended: false })); //Parse URL-encoded bodies
app.use(express.json()); //Used to parse JSON bodies
app.use(compression({
filter:shouldCompress,
threshold: 3
}));
app.use(express.static('public'));
app.disable('x-powered-by');
// Initialize Passport and restore authentication state, if any, from the session.
var passport = require('passport');
app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session())
// Routes
app.use('/', require('./routes/index'));
app.use('/member', require('./routes/users'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on port: ${PORT}`));
routes/users.js
const express = require('express');
const router = express.Router();
/* GET authentication funcs */
let authentication = require('../controllers/auth.js');
router.get('/subscribe', (req, res) => { res.render('subscribe'); });
router.post('/subscribe', authentication.subscribe);
module.exports = router;
controllers/auth.js
require('dotenv').config();
const model = require("../models");
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const FacebookStrategy = require('passport-facebook').Strategy;
passport.serializeUser(function(user, done) {
done(null, user)
});
passport.deserializeUser(function(email, done) {
done(null, email)
})
function validateLead(req, done) {
mail = req.body.lead_email;
console.log('validateLead() called!');
models.Lead.findOne({
where: {
email: email
}
}).then(/* some logic */).catch();
} else {
// email already taken ..
return done(null, false, {
message: 'This email address is already subscribed'
});
}
}).catch((err) => {
console.log('An error occurred!', err);
});
}
exports.subscribe = function(req, res, next) {
switch (req.body.source) {
case 'facebook':
passport.use(new FacebookStrategy({
clientID: process.env.FACEBOOK_APP_ID,
clientSecret: process.env.FACEBOOK_APP_SECRET,
callbackURL: process.env.FACEBOOK_CALLBACK_URL
},
function(accessToken, refreshToken, fbProfile, done) {
console.log('FB callback!');
profile = {
'email': fbProfile.email,
'firstName': '',
'LastName': '',
'leadSource': '',
'tags': [],
};
return validateLead(req, done, profile);
}
));
break;
default:
console.log('Unknown');
}
}
views/test.eps
<a href='#'><i id='facebook' class='foobar'></i></a>
(simplified) views/layout.eps
$(document).ready(function(){
$('i.foobar').click(function(e){
$.ajax({
method: "POST",
url: "/member/subscribe",
data: {
"source": $(this).attr('id')
},
dataType: "json",
timeout: 5000 // 5000ms
}).done(function(data) {
// is called if request is successful
console.log(data.fridge);
}).fail(function(jqXHR, status) {
// is called if request fails or timeout is reached
alert('Request could not complete: ' + status);
});
});
});
I have put console.log() messages in controllers/auth.js and I can see that the FB code branch is being reached. However, when log messages in validateLead() and the FB callback function are not being reached.
What is the cause of this, and how do I fix it?
A couple things I can see :
As far as I could see you didn't configure passportjs. You need to have a configuration file, which for you would be the controllers/auth.js. To configure passport you need to run require('./controllers/auth')(passport); in app.js.
For passport to be able to ingest that config you need to export them as a function that takes passport e.g. module.exports = passport => {passport.use('facebook')}
Your config file (in exports.subscribe) is not a format that passport will understand. Follow the Documentation on how to create that config file.
Passport provides you with authentication middleware, I am pretty sure that you cannot create "wrappers" for them like in controllers/auth.js. To access passport's auth functions you use passport.authenticate('facebook', callback())(req, res, next) in routes/users.js.
Passport only provides middleware to serialize and deserialize users.
Your deserialization is not yet set up. You need a call to the db to fetch the user from session store.

How to debug EJS

There are several answers for this question, but they're all several years old and no longer relevant/safe to use.
Since EJS is rendered as html in the browser, there's no way to inspect it in the browser dev tools
The EJS.co site says that the errors/logs should show in the terminal just like node errors, but that's not the reality for me, somehow.
I used the command npx express-generator to bootstrap my project, and I'm wondering if there isn't a debugger of some kind in there that is overriding how EJS is supposed to send errors?
I say this because when EJS has an error, the only thing my terminal shows is something like GET /users/dashboard 500 26.5 ms with nothing else. And then of course the browser shows the default message for 500 errors, which isn't helpful.
I'll throw in my app.js in case someone smarter than me can see the issue there:
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const rfs = require('rotating-file-stream')
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
require('mongoose-type-url');
// const serveFavicon = require('serve-favicon');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const expressSession = require('express-session');
const methodOverride = require('method-override');
const expressSanitizer = require('express-sanitizer');
const sgMail = require('#sendgrid/mail');
// create a rotating write stream
const accessLogStream = rfs.createStream('access.log', {
interval: '1d', // rotate daily
path: path.join(__dirname, 'log')
});
const User = require('./models/user');
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const formsRouter = require('./routes/forms');
const companiesRouter = require('./routes/companies');
const locationsRouter = require('./routes/locations');
const app = express();
if (app.get('env') == 'development'){ require('dotenv').config(); };
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
//connect to database
mongoose.connect(process.env.DATABASE_URL,{
useNewUrlParser:true,
useUnifiedTopology:true,
useFindAndModify: false,
useCreateIndex:true
}).then(() => {
console.log('Connected to Mongo DB')
}).catch(err => {
console.log('error: ',err.message)
});
// view engine setup
//use ejs-locals for all ejs templates
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev', { skip: function (req,res) { return res.statusCode < 400} }));
app.use(logger('common', { stream: accessLogStream }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(methodOverride("_method"));
app.use(expressSanitizer());
var expiryDate = new Date(Date.now() + 60 * 60 * 1000 * 6) // 6 hours
app.use(expressSession({
secret:"surfs up brah",
resave:false,
saveUninitialized:false,
name: 'sessionId',
secure:true,
httpOnly:true,
expires: expiryDate
}));
app.use(passport.initialize());
app.use(passport.session());
app.disable('x-powered-by');
app.use(function(req, res, next){
res.locals.currentUser = req.user;
next();
});
// CHANGE: USE "createStrategy" INSTEAD OF "authenticate"
passport.use(User.createStrategy({usernameField:'personalEmail'}));
// use static authenticate method of model in LocalStrategy
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
//set local variables middleware
app.use(async function (req,res,next) {
if (app.get('env') == 'development'){ req.user = await User.findOne({firstName: 'potato'}); };
res.locals.currentUser = req.user;
//set default page title if one is not specified
res.locals.title='Custom Forms';
//set success flash message
res.locals.success = req.session.success || "";
//delete flash message after sending it to the page so it doesn't show again
delete req.session.success;
//set error flash message
res.locals.error = req.session.error || "";
//delete flash message after sending it to the page so it doesn't show again
delete req.session.error;
//continue on to the next function in the middlware/route chain
next();
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/forms', formsRouter);
app.use('/companies', companiesRouter);
app.use('/locations', locationsRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
const { seedDatabase, clearDatabase, seedDefaultQuestions, clearRecentItems} = require('./seeds.js');
async function databaseInit() {
await clearRecentItems();
// await seedDefaultQuestions();
// await clearDatabase();
await User.register({firstName: 'potato', lastName:'head',username:'potatohead', personalEmail:'test#test.com', role:'Owner'},'password');
// await seedDatabase();
}
databaseInit();
let port = process.env.PORT;
if (port == null || port == "") {
port = 8080;
}
app.listen(port, () => {
console.log("server has started, listening on port "+port);
});
module.exports = app;
Here's an example route:
app.get('/dashboard', (req,res) => {
const currentCompany = Company.findById(req.params.id);
res.render('../views/company/profile', {currentCompany});
}
And some sample EJS:
<html>
<body>
<h1><%= currentCompany.name %></h1>
</body>
</html>
Now say I didn't wrap the findById call in a try block and it didn't find a document, then tried to render the page using an undefined or null object. The EJS file wouldn't have anything to which to refer for currentCompany.name (by the way, I do indeed try/catch and handle errors).
This is where the terminal just logs the simple 500 error, and refuses to load anything at all.
Another example of issues I've had with EJS:
<html>
<body>
<&- include('../../partials/header) %>
</body>
</html>
Here, it would throw the exact same 500 error because I went up one too many folders in the path for that partial. Absolutely nothing else shown anywhere.
Thanks to #LawrenceCherone, the issue is the default error handler created when npx express-generator is used.
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
Without that, the EJS error information (including line number, etc) gets displayed in the browser.

Node.JS and Postgres Search Bar

Im trying to create a search bar that will query and display the data from my own Postgres database. I have a search bar on my screen, and I think I am connected to my database, but i cannot get any results to show up. Any help would be appreciated. Im still quite new to using node.js and developing tools such as this. When i submit my search, i receive a 404 error message.
Index.js
const express = require('express');
const router = express.Router();
const pg = require('pg');
const path = require('path');
const connectionString = process.env.DATABASE_URL || 'postgres://postgres:postgres#localhost:5432/todo';
router.get('/', (req, res, next) => {
res.sendFile(path.join(
__dirname, '..', '..', 'client', 'views', 'index.html'));
});
router.get('/api/v1/todos', (req, res, next) => {
const results = [];
// Get a Postgres client from the connection pool
pg.connect(connectionString, (err, client, done) => {
// Handle connection errors
if(err) {
done();
console.log(err);
return res.status(500).json({success: false, data: err});
}
// SQL Query > Select Data
const query = client.query('SELECT name FROM world_heritage_sites.caravanserai ORDER BY iso ASC;');
// Stream results back one row at a time
query.on('row', (row) => {
results.push(row);
});
// After all data is returned, close connection and return results
query.on('end', () => {
done();
return res.json(results);
});
});
});
App.js
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const routes = require('./server/routes/index');
// var users = require('./routes/users');
const app = express();
// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'html');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'client')));
app.use('/', routes);
// app.use('/users', users);
// catch 404 and forward to error handler
app.use((req, res, next) => {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json({
message: err.message,
error: {}
});
});
module.exports = app;
HTML
<!DOCTYPE html>
<html ng-app="nodeTodo">
<head>
<title>Todo App - with Node + Express + Angular + PostgreSQL</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/search.js" type="text/javascript"></script>
<script src="/search.js"></script>
<script src="//code.jquery.com/jquery-2.2.4.min.js" type="text/javascript"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body ng-controller="mainController">
<div class="container">
<div class="header">
<h1>SuckySearchBar</h1>
<hr>
<h1 class="lead">Designing Search Bars Suck This Never Works</h1>
</div>
</body>
<body ng-controller="searchController">
<div class="container">
<div class="search-box">
<input class="search" type="text" placeholder="Search" id="search" method='GET' autocomplete="on" onkeyup="search();">
<table class="result table-bordered" id="search"></table>
<script>
function searchinput(){
$.ajax({
type: 'GET',
url: '/api/v1/todos' + searchinput,
success: function(result){
window.location.reload(true);
}
})
}
</script>
</div>
</body>
</html>
Search.js
function search(search_string, func) {
pool.query(
"SELECT name FROM world_heritage_sites.caravanserai ORDER BY iso ASC",
[search_string],
function(err, result) {
if(err) {
func([])
} else {
func(result.rows)
}
}
);
}
module.export = search;
first of all, congrats for starting a new studies task! But let's solve this issue, shall we?
1 - My tip for you, is that before you even start to worry about the frontend, let's make sure that our service is running fine, and we shall test it on the server-side only. "I think I am connected to my database", we cannot proceed if we think something is going on fine, we need to make sure!
2 - We need our service running, that`s the only way we can get our DB connected. So for now, we forget about the interface and DB, let's focus on the service:
Inside your "app.js" you are trying to import your routes right? By doing
const routes = require('./server/routes/index');
But in order to do that, you need to export those routes before, then go to your "index.js" file and add "module.exports = router". Now you can use your router imported inside your "app.js" file!
Stays like this:
const express = require('express');
const router = express.Router();
const pg = require('pg');
const path = require('path');
const connectionString = process.env.DATABASE_URL || 'postgres://postgres:postgres#localhost:5432/todo';
Almost there, our service needs to listen to some port now
router.get('/', (req, res, next) => {
res.sendFile(path.join(
__dirname, '..', '..', 'client', 'views', 'index.html'));
});
router.get('/api/v1/todos', (req, res, next) => {
console.log("HAHAHAHAHA")
const results = [];
// Get a Postgres client from the connection pool
pg.connect(connectionString, (err, client, done) => {
// Handle connection errors
if(err) {
done();
console.log(err);
return res.status(500).json({success: false, data: err});
}
// SQL Query > Select Data
const query = client.query('SELECT name FROM world_heritage_sites.caravanserai ORDER BY iso ASC;');
// Stream results back one row at a time
query.on('row', (row) => {
results.push(row);
});
// After all data is returned, close connection and return results
query.on('end', () => {
done();
return res.json(results);
});
});
});
module.exports = router;
Now our application needs to listen to some port. I don't have access to your folder structure, that's why I will work the idea using only these two files you presented us. Inside your "app.js" you got tell your application to serve using one port, you can do that by typing
"app.listen(8000, () => console.log('listening'))
"
since you are exporting your app, you can import and use it anywhere you'd like, but I told you already, I will work the idea restricted to the files you showed us, that's why your "app.js" would be like this
check this Docs before : https://node-postgres.com/features/connecting
const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const routes = require('./index');
// var users = require('./routes/users');
const app = express();
// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'html');
// uncomment after placing your favicon in /public
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'client')));
app.use('/', routes);
// app.use('/users', users);
// catch 404 and forward to error handler
app.use((req, res, next) => {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json({
message: err.message,
error: {}
});
});
app.listen(8000, () => console.log('listening'))
module.exports = app;
Ok, now our service is running, go to your terminal and type: node app.js
it should print "listening" in your shell.
Now try to access http://localhost:8000/api/v1/todos in your browser, it should print an error "pg.connect is not a function"
That's because you are not using the lib the right way, try something like this
const express = require('express');
const router = express.Router();
const path = require('path');
const { Pool, Client } = require('pg')
const connectionString = 'postgres://postgres:postgres#localhost:5432/todo'
const client = new Client({
connectionString: connectionString,
})
client.connect()
router.get('/', (req, res, next) => {
res.sendFile(path.join(
__dirname, '..', '..', 'client', 'views', 'index.html'));
});
router.get('/api/v1/todos', (req, res, next) => {
const results = [];
client.query('SELECT name FROM world_heritage_sites.caravanserai ORDER BY iso ASC;', (err, res) => {
console.log(err, res)
client.end()
})
});
module.exports = router;
But remember, you need to have your Postgres service running in your localhost to connect using this connection string you are using. If you configured your Postgres service and db the right way, it should work fine, then you just need to call your route "localhost:8000/api/v1/todos" in your interface.
Actually there are a lot of things you should check in your code, and maybe it's good if you get some background before start this project. Try some tutorials for beginners on youtube and check other dev's code. Good Luck and Good code dude!
I hope I gave you at least a little help :)
I think what #Molda is saying is that you should change methods=['GET'] to method='GET'. Can you post the surrounding html as well?
EDIT
Ok, so I think you are confusing the javascript running on your server and the javascript running in the browser. If you are going to call search() from the onKeyUp() event handler Then it is going to run in the browser. Since it is going to run in the browser, it does not have the ability to access postgres directly. What it should do is make an ajax request to a route on the server that provides it with the search results as json (similar to what you did with /api/v1/todos you could define /api/v1/search), which it then renders on the page somehow (perhaps with jquery). In this case, you shouldn't even need to define method on your input.

Router not firing .find or .findByID in express app. Using nextjs as well

I am using a NextJS/MERN stack. My NextJS is using my server.js file, along with importing the routes for my API. The routes appear to be working as they do show activity when firing an API call from Postman or the browser. However, this is where the activity stops. It's not getting passed the Model.find() function as far as I can tell. I am not sure if this has to do with Next js and the prepare method in the server.js, or if this is related to the bodyparser issue.
Here is my server.js
const express = require("express");
const urlObject = require('./baseURL')
const passport = require("./nextexpress/config/passport-setup");
const passportSetup = require("./nextexpress/config/passport-setup");
const session = require("express-session");
const authRoutes = require("./nextexpress/routes/auth-routes");
const KBRoutes = require("./nextexpress/routes/kb-routes");
const userRoutes = require('./nextexpress/routes/user-routes')
const pollRoutes = require('./nextexpress/routes/poll-routes')
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser"); // parse cookie header
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const nextapp = next({ dev })
const handle = nextapp.getRequestHandler()
const bodyParser = require('body-parser');
// mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/kb', { useNewUrlParser: true });
mongoose.connect('mongodb://localhost:27017/kb')
console.log(process.env.MONGODB_URI)
const connection = mongoose.connection;
const baseURL = urlObject.baseURL
const PORT = process.env.PORT || 3000
connection.once('open', function () {
console.log("MongoDB database connection established successfully");
})
nextapp.prepare().then(() => {
const app = express();
console.log(process.env.PORT, '----port here ----')
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/api/auth", authRoutes);
app.use("/api/kb", KBRoutes);
app.use('/api/user', userRoutes)
app.use('/api/poll', pollRoutes)
app.get('/posts/:id', (req, res) => {
return nextapp.render(req, res, '/article', { id: req.params.id })
})
app.get('/redirect/:id', (req, res) => {
return nextapp.render(req, res, '/redirect')
})
app.all('*', (req, res) => {
return handle(req, res)
})
app.listen(PORT, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${PORT}`)
})
})
// connect react to nodejs express server
And the relevant route:
KBRoutes.get('/', (req, res) => {
console.log(KB.Model)
KB.find({}, (err, photos) => {
res.json(kbs)
})
})
I am able to get to each one of the routes. Before this was working, when I had the NextJS React portion split into a separate domain therefore separate server.js files. Once I introduced NextJs thats when this problem arose. Any help would be greatly appreciated.
It looks like the relevant route is trying to return json(kbs), but kbs doesn't seem to be defined. Returning the result of your find query would make more sense to me, including a nice error catcher and some status for good practice. Catching errors should tell you what's going wrong, i would expect an error in your console anyway that would help us out finding the answer even more.
KB.find({}, (err, photos) => {
if (err) res.status(401).send(err)
res.status(200).json(photos)
})

Categories

Resources