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;
CodePudding user response:
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.
CodePudding user response:
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.
