I have a simple app with database and i am having issues with controller function. It's not getting executed for some reason that i couldn't figure it out and it drove me crazy. I will be so grateful if you guys could help with me this.
userController.js
exports.insertUser = async (req, res, next) => {
try {
const user = await MySQL.insertRecord(User, { ...req.body })
res.status(201).send(user)
} catch (e) {
res.status(500).send(e)
}
}
insertion function in db.js
static async insertRecord (User, body) {
console.log(1) // for debugging purposes
const user = User.build(body)
try {
await user.save()
console.log('Record saved to database succesfully.')
return user
} catch (e) {
throw e
}
}
userRoutes.js
const express = require('express')
const userController = require('../controllers/userController')
const router = express.Router()
router
.post('/signup', userController.insertUser)
module.exports = router
server.js
(async () => {
const express = require('express')
require('dotenv').config()
const path = require('path')
const { Sequelize } = require('sequelize')
const MySQL = require('./database/db')
await MySQL.connect(Sequelize)
const userRouter = require('./routes/userRoutes')
const app = express()
const PORT = process.env.PORT || 3000
// setting ejs as the templating language
app.set('view engine', 'ejs')
// middlewares
app.use(express.json())
app.use(express.static(path.join(__dirname, 'public')))
app.use('/user', userRouter)
app.listen(PORT, () => console.log(`server listening on port: ${PORT}`))
})()
Here my insertRecord function is not getting executed. It doesn't log 1.
Related
I am trying to add an image to my index.ejs file, but my code is not pulling the image from the /image folder specified in my second code block. Can anyone help me find the solution to my issue?
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const { path } = require('express/lib/application');
const { HTTPRequest } = require('puppeteer');
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://127.0.0.1:27017';
app.use('/public/images', express.static('/public/images'));
//setup connection
MongoClient.connect(url, {useUnifiedTopology: true})
.then(client => {
console.log('connected to database');
const db = client.db('user-signup-info');
const manateeCollection = db.collection('manatees');
})
//----------middleware------------
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
//----------routes----------------
//going to index.ejs and reading database entries
app.get('/', (req, res) =>{
db.collection('manatees').find().toArray()
.then(manatees => {
res.render('index.ejs', {manatees: manatees})
})
.catch(/*....*/)
})
//grabbing form data and adding to database
app.post('/manatees', (req, res)=>{
//console.log(req.body);
manateeCollection.insertOne(req.body)
.then(result =>{
//console.console.log(result);
res.redirect('/');
})
.catch(error => console.error(error));
})
//----------server----------------
app.listen(3000, function(){
console.log('server is running');
})
//----------end of connection-----
.catch(console.error);
<img src="/images/Manatee_CGrant_VisitCitrus-1200x500.jpg">
Try to change your middleware to -
app.use(express.static('public/images'))
one question. I am making an api with node,express and mysql.
And there seems to be an error when I run nodemon.
If anyone knows anything, it would be appreciated.
Error:
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
My index.js:
const express = require('express')
const app = express()
const routes = require("./routes/transactions")
//Settings
app.use('port', process.env.PORT || 3000)
//Middlewares
app.use(express.json())
//Routes
app.use("/", routes.transactions)
//Crear servidor con el puerto
app.listen(app.get('port'), () => {
console.log('Hola Mundo', app.get('port'))
})
module.exports = app;
My routes/transactions.js
const express = require('express');
const router = express.Router();
const mysqlConnection = require('../database');
router.get('/transactions', (req, res) => {
mysqlConnection.query('SELECT * FROM transactions', (err, rows, fields) => {
if(!err) {
res.json(rows)
} else {
console.error(err)
}
});
});
exports.transactions = router
My database.js
const mysql = require('mysql');
const mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'operations',
})
mysqlConnection.connect(function(err){
if(err) {
console.log(err);
return
} else {
console.log('Db is connected')
}
})
module.exports = mysqlConnection;
You are mistakenly using app.use() instead of app.set().
Change this:
app.use('port', process.env.PORT || 3000)
to this:
app.set('port', process.env.PORT || 3000)
The error comes because you're passing a string or number to app.use() where it expects a middleware function reference.
It seems like you should have had a stack trace for this error (if you learn how to interpret it) that points to the exact line of code (a few steps up the stack) causing the problem which should simplify debugging next time.
I think the error here is resulting from the overload of app.use():
You can use this function in two ways, to use middleware and routes.
routes/transactions.js should be altered to the following:
const router = express.Router();
const mysqlConnection = require('../database');
router.get('/transactions', (req, res) => {
mysqlConnection.query('SELECT * FROM transactions', (err, rows, fields) => {
if(!err) {
res.json(rows)
} else {
console.error(err)
}
});
});
exports.transactions = router
In index.js:
const express = require('express')
const app = express()
const routes = require("./routes/transactions")
//Settings
app.use('port', process.env.PORT || 3000)
//Middlewares
app.use(express.json())
//Routes
app.use("/", routes.transactions)
//Crear servidor con el puerto
app.listen(app.get('port'), () => {
console.log('Hola Mundo', app.get('port'))
})
module.exports = app;
This would run the code in the 'get' endpoint in 'routes/transactions.js' when you navigate to localhost:<port>/transactions.
I'm a new learner express.js I want to test simple post and get operations with tdd mechanism. I created the test, route, index and db files but when I try to test POST method it gives me this error.
This is my routes/task.js
const express = require('express');
const router = express.Router();
router.post("/api/task", async (req,res) => {
try {
const task = await new Task(req.body).save();
res.send(task);
} catch (error) {
res.send(error);
}
})
This is my test/task.js
let chai = require("chai");
const chaiHttp = require("chai-http");
const { send } = require("process");
let server = require("../index");
//Assertion Style
chai.should();
chai.use(chaiHttp);
describe('Tasks API', () => {
/**
* Test the POST Route
*/
describe('POST /api/task', () => {
it("It should POST a new task", () => {
const task = {task: "Wake Up"};
chai.request(server)
.post("/api/task")
.send(task)
.end((err, response) => {
response.should.have.status(201);
response.body.should.be.a('string');
response.body.should.have.property('id');
response.body.should.have.property('task');
response.body.should.have.property('task').eq("Wake Up");
response.body.length.should.be.eq(1);
done();
});
});
});
});
This is my db.js
var sqlite3 = require('sqlite3').verbose()
const DBSOURCE = "db.sqlite"
let db = new sqlite3.Database(DBSOURCE, (err) => {
if (err) {
// Cannot open database
console.error(err.message)
throw err
}else{
console.log('Connected to the SQLite database.')
db.run(`CREATE TABLE IF NOT EXISTS todo (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task text
)`,
(err) => {
if (err) {
// Table already created
console.log(err);
}
});
}
});
module.exports = db
And this is my index.js
const connection = require('./db');
const express = require('express');
const app = express();
const cors = require("cors");
const port = process.env.PORT || 8080;
app.use(express.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello World');
});
app.post('/api/task', (req, res) => {
res.status(201).send(req);
});
app.listen(port, () => console.log(`Listening on port ${port}...`));
module.exports = app;
The thing that I try to do is building a test case to test the post method. I think I couldn't built the correct relations the files.
Currently, just by doing a POST request to /api/task, the error will appear. That is because of these lines in index.js:
app.post('/api/task', (req, res) => {
res.status(201).send(req);
});
The req parameter is circular, hence cannot be JSON-stringified.
Solution
In routes/task.js export the router:
const express = require('express');
const router = express.Router();
router.post("/api/task", async (req,res) => {
try {
const task = await new Task(req.body).save();
res.send(task);
} catch (error) {
res.send(error);
}
})
// By adding this line you can export the router
module.exports = router
In index.js, include the routes/task.js file and pass it to app.use(...), also remove the now-obsolete /api/task route:
const connection = require('./db');
const express = require('express');
const app = express();
const cors = require("cors");
const taskRoutes = require("./routes/task")
const port = process.env.PORT || 8080;
app.use(express.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello World');
});
app.use(taskRoutes)
app.listen(port, () => console.log(`Listening on port ${port}...`));
module.exports = app;
This way we got rid of the circular structure stringifying and the tests should now pass.
I`m trying to create emit for the socket on post request from postman but got some troubles. I found an issue here but it seems not working for me. I have this code in my app.js
App.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const http = require('http').createServer(app)
const eventsRoute = require('./routes/eventsRoute')
const io = require('socket.io')(http, {
cors: {origin: "*"},
path: '/api/events'
})
io.of('/api/events/').on('connection', socket => console.log('connected'))
...
app.use('/api/events', eventsRoute(io))
module.exports = app
And here I got eventsRoute.js code. Here, I think, is the main problem
eventsRoute.js
const express = require('express')
const errorHandler = require('../utils/errorHandler')
const router = express.Router()
const returnRouter = io => {
router.post('/', async (req, res) => {
try {
io.sockets.emit('create', req.body)
res.status(200).json({message: 'successful'})
} catch (e) {
errorHandler(e)
}
})
router.get("/", function (req, res) {
try {
res.send({})
} catch (e) {
errorHandler(e)
}
})
return router
}
module.exports = returnRouter
And on my client side, I have some code in the script tag. Here it is
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js"></script>
<script>
const socket = io('ws://localhost:5000', {path: '/api/events'})
socket.on('create', data => {
console.log(data)
})
</script>
So, the main reason was in ... all files. Let's begin with index.js. I'm exporting the app. Instead of that, I have to export http. Then in app.js, I will have to change line with sockets to this
const io = require('socket.io')(http, options)
io.of('/api/events')
.on('connection', socket => {
app.use('/api/events', eventsRoute(socket))
})
I have been getting a problem when I want to module.export the pool variable to use it in other files. I have this program in src\db\index.js:
const {Pool} = require('pg');
const express = require('express');
//Initialize
const path = require('path');
const app = express();
const fetch = require('fetch');
const PORT = process.env.PORT || 5000;
//Global Variables
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl:true
});
//Setting
app.use(express.static(path.join(__dirname, 'public')));
//Routes
app.use(require('../Routes/logIn'));
app.use(require('../Routes/singIn'));
app.use(require('../Routes/forgotPass.js'));
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
module.exports = pool;
And then I want to require the const pool in this file src\Routes\LogIn.js:
const express = require('express');
const pool = require('../db');
const router = express.Router();
router.get('/usuario/:user', function (req, res) {
//console.log("GET usuario");
var user = req.params.user;
pool.query(
`select * from users where email = '${user}' limit 1`,
function (error, resq, fields) {
if (error) {
console.log(error);
} else {
console.log(user);
res.send(resq.rows);
}
}
);
});
module.exports = router;
But when I run the index.js and go to the route ulr/usuario/:user, in the logs I see that the program has an error that says "pool.query is not a function". I want to know how i could export the const pool to use it in other files.
You can use
module.exports = {
query: (text, params) => pool.query(text, params),
}
Use express-promise-router
const Router = require('express-promise-router')
const db = require('../db')
const router = new Router()
Use
await db.query(`
SELECT * from local
`)
instead of pool.query in your router.get or router.post
The above should solve your issue - You can check the same reference here
https://node-postgres.com/guides/async-express