I'm creating a programmer job board app and I'm trying to display json data on my main page. At some point I'll render it, but for now I'm just trying to get it to show up in json form so that I know it works.
I'm able to connect to the server, but when I load the page I get a TypeError (Job.showAllJobs is not a function).
I'm using a crud app I made the other week as a reference, but there are a few differences between it and this project that are throwing me off.
Here's my project's file structure:
job-board
database
connection.js
schema.sql
models
Job.js
User.js
views
index.ejs
login.ejs
server.js
Unlike my previous crud app, this project is using a connection.js file that gave some trouble earlier. At first I thought I was out of the woods, but I think it might be responsible for my current problem.
Not getting GET to work might seem like a minor error, but it's really bugging me and I haven't been able to keep working because of it.
I populated my table (jobs) with a sample listing as a test, but in the very near future I plan on connecting the app to the GitHub jobs api.
server.js:
const express = require('express');
const app = express();
const PORT = 3000;
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const Job = require('./models/Job');
const User = require('./models/User');
const connection = require('./database/connection')
app.use(bodyParser.json())
app.use(methodOverride('_method'));
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.set("view engine", "ejs");
///// GET /////
// GET INDEX
app.get('/', (request, response) => {
Job.showAllJobs().then(everyJob => {
response.json('index');
// response.render('index', { jobs: everyJob });
});
});
Job.js
const Job = {};
const db = require('../database/connection');
///// JOBS /////
/// INDEX ///
Job.showAllJobs = () => {
return db.any('SELECT * FROM jobs');
};
module.exports = Job;
module.exports = db;
connection.js
// require database setup to use pg-Promise
const pgp = require('pg-promise')({});
// connection url
const connectionURL = "postgres://localhost:5432/job_board";
// new database connection
const db = pgp(connectionURL);
// module.exports = db;
You have a couple of problems here.
Make sure you're passing the jobs into res.json instead of the string 'index'
Make sure you're exporting db from connection.js
You're exporting both Job and db from Job.js. Since you're exporting db second, it's overriding the export of Job.
Related
I am writing a code that allows me to connect to the MongoDB database that I had made. For some reason, I am getting errors connecting my page and I don't know why. I have already looked at TypeError: connection.once(...).catch is not a function for help but that page did not answer my question. I also copied the code that my professor made and I can't seem to get it working.
This is my code:
const express = require('express');
const app = express();
const connection = require('./db/connection.js');
const dotEnv = require('dotenv').config();
connection.once('open', ()=>{
const server = app.listen(process.env.PORT || 8080, ()=>{
console.log("Connected and listening");
});
});
app.use(express.static('public'));
app.use(express.urlencoded({extended:true}));
const Film = require('./models/film.js');
And this one is the connection.js file
const mongoose = require("mongoose");
let mongoDB = `name of database (this is correct, I used this to connect to a different project and it worked`;
module.exports = mongoose.connect(mongoDB);
hy, I'm learning nodeJS but when do post using postman data is saving in db but not displaying response in POSTMAN. On postman just displaying sending request... .
const express = require("express")
const app = express()
// dbConnection
require('./mongo')
// Models
require('./model/Post')
// MIDDLEWARE
app.use(express.urlencoded({extended: true}));
app.use(express.json())
const mongoose = require('mongoose')
const Post = mongoose.model("Post")
// POST REQUEST
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
res.status(500)
}
})
app.listen(8000, ()=>{
console.log('Server is running on port:8000')
})
I don't think you're even running on a port, it says here
console.log('Server is running on port:8000')
})
All you do is console.log Server is running on Port 8000 with no back tick, therefore your not even running your server. This is why I think your Code is not working, test it out and see, if you get an error then you can debug from there. At least put some effort into debugging rather than immediately going on stack overflow. replace what you done with the port with this
// Create a variable called port and set it to your desired port
const port = 8000;
// Then hook it up to express.
console.log(`Server is running on port: ${port}`)
})
If the problem is still there then I think I have the solution to it
Check if you have mongoose and express installed
(it's npm i mongoose express)
I don't think you're even connected to your mongoose server, try doing this
const express = require("express")
const app = express()
// dbConnection
require('./mongo')
// Models
require('./model/Post')
// MIDDLEWARE
app.use(express.urlencoded({extended: true}));
app.use(express.json())
const mongoose = require('mongoose')
const Post = mongoose.model("Post")
// Hook it up to res
const port = 8000
// POST REQUEST
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
res.status(500)
}
})
// Mongoose Connection
mongoose
.connect("your connection (it should be connection to application on mongo)", {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true
})
.then(() => {
console.log("Connected to the database");
})
.catch((err) => {
console.log(err);
});
app.listen(8000, ()=>{
console.log(`Server is running on port: ${port}`)
})
Then once you've finished that, you established a connection to the mongodb server and should send the request to post
I think the catch block is executed. In this block, you only set the status of the response to 500 but you don't actually send the response to the client. That's why the Postman screen keeps blocking.
So, there are 2 things:
you need to send something to the client
you need to log the error to debug.
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
console.log(error);// for debugging
res.status(500).send("ERROR_SERVER"); // send something to client
}
})
I have found the answer for your error, as I said in my old answer, running your tests would've worked, and showed you the error, however I have found the answer, I am assuming you have already found the solution (which is probably the same solution as mine) but if you haven't here's the problem.
The problem
It's very simple, you're creating a variable for mongoose after you required mongoose require('./mongo'); const mongoose = require('mongoose') This is wrong as JavaScript and most programming languages read code line by line (if not then all) so change this up to be instead the following:
Solution
const mongoose = require('mongoose');
require('./mongo');
Information
Create the variable before you require the package like so (in your code example):
const mongoose = require('mongoose');
require('./mongo');
If you have more problems
If you do have more problems then try to reinstall/update the package dependency for mongoose as following:
yarn add mongoose
or
npm install mongoose
If you do still have problems after the only think I can ask you to do is to change the line of code when it says
require('./mongo');
to either
require('./{filename}'); // Whatever the actual filename is.
or:
require('./mongoose');
Tips to improving your question
Even if my question doesn't work for your code make sure to paste the error message or the important parts of the error message into the question, otherwise this makes it hard to pinpoint what your error is. This makes it easier to find the solution for your code.
i have a node.js back-end with express sever.
i have routes called templete.rpoutes.js:
const express = require("express");
const templateCtrl = require("../controllers/template.controller");
const router = express.Router();
router.route("/createtemplate").post(templateCtrl.createTemplate);
router.route("/uploadFinalTemplate").post(templateCtrl.uploadFinalTemplate);
// beneath are the routes with issue
router.route("/:templateId/productInfos").get(templateCtrl.productInfos);
router.route("/:templateId").get(templateCtrl.Read);
// router.param("templateId", templateCtrl.templateByID);
module.exports = router;
I have the defined method in template controller where i'm just logging stuff. no backend logic is there yet. so I expect when I make a call to these end point, i should get those logs displayed
I have configured express server as:
app.use("/api/template", templateRoute);
app.use("/api/productInfo", productInfoRoute);
app.use('/api/sendInformation', Notify)
// PORT
const port = process.env.PORT || 5000;
const server = app.listen(port, () => {
console.log("Connected to port " + port);
});
Note: the app is express.router() method and the controllers are required correctly and the other end-points work for the same controller.
so when I send a get request from postman to localhost:5000/api/template/5f870cd3b02fd77d0a576a54 I get a 404 and Not found in my console like this: (Plus the server is running)
as described in the documentation https://expressjs.com/en/guide/routing.html#express-router
const router = express.Router();
router.post("/createtemplate",templateCtrl.createTemplate);
router.post("/uploadFinalTemplate",templateCtrl.uploadFinalTemplate);
router.get("/:templateId/productInfos",templateCtrl.productInfos);
router.get("/:templateId",templateCtrl.Read);
I am creating an MVC structured app. For me this is a new concept. I am having trouble as where to place my middleware. Here's how my app is structured:
Server:
//routes
app.use('/' , userRoutes);
User routes :
//controllers
const postUser = userController.postUser;
const getUser = userController.getUser;
//route
router.route('/user').post(postUser).get(getUser);
And my controllers :
const {check, validationResult } = require('express-validator');
const postUser = (req,res) => {
res.send(req.body);
console.log('POSTED')
};
const getUser = (req,res) => {
res.send(req.body );
console.log('GOTTEM');
};
module.exports = {postUser , getUser};
Where in this bunch should i implement my middleware. I want to use express-validator to check for fields etc, so it has to sit in between the requested path and the callback. Im a bit confused as to where to add my middleware.
It's My Suggestion to use express Boiler Plate for Better MVC Directory Structure and better Routes Understanding.
So after trying some things out myself i've figured it out.
In my routers where i chain all the methods to a specific route:
router.route('/user').post(middleware,postUser).get(getUser);
This worked for me.
I'm building a node.js server and my folder structure looks like this:
server.js
app/routes.js
app/routes/users.js
My problem is that i'm not sure how can i use the app variable inside the users.js file. Do i have to require and setup express again in this file or is there a better/easier way to do it? Here is my sample code(just the bare minimum to understand my problem):
server.js
// Include our packages in our main server file
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();
// Init Stormpath for user management and authentication
app.use(stormpath.init(app));
// Load routes
require('./app/routes')(app);
// Start the server
app.listen(process.env.PORT);
// Stormpath will let you know when it's ready to start authenticating users.
app.on('stormpath.ready', function () {
console.log('Your server is running on port ' + port + '.');
});
app/routes.js
// Import dependencies
const express = require('express');
const stormpath = require('express-stormpath');
// Export the routes for our app to use
module.exports = function(app) {
// Create API group routes
const apiRoutes = express.Router();
// User management: get users, invite users, view user profile
var UsersRoute = require('./routes/users');
apiRoutes.get('/memberinfo', stormpath.loginRequired, UsersRoute.memberInfo);
// Set url for API group routes
app.use('/', apiRoutes);
};
app/routes/users.js
// Protected route test
module.exports.memberInfo = function(req, res){
//how do i access the "app" here?
res.status(200).send({ user: req.user });
}
In your .memberInfo method, you can use req.app to access the app object that is associated with that request.
In cases where you aren't passed a req object that you can use in this way, then you need to initialize the module by calling a method on it and passing it the app object and the module can then store the app object locally so it can use it when desired.