简体   繁体   中英

Express js routing and mysql query not working

I'm just now started to learn Node and Express, I have some probelm with the routes in express. I want a well modular code for routing. I want to query some data from mysql database:

Here is my app.js(it is on "public_html" directory):

var path = require('path');
var express = require('express');
var routes = require('./routes');
var app = express();

var staticPath = path.resolve(__dirname, './');
app.use(express.static(staticPath));

routes.init(app);
module.exports = app;

app.listen(3000, function() {
console.log('Server is listening on port: 3000');
});

Next file: "public_html/routes/index.js":

exports.init = function(app){

//electronics routes
app.use('/laptop', require('./laptop'));
};

"public_html/routes/laptop/index.js":

var router = require('express').Router();
router.get('/laptop', require('./modules/laptop'));
module.exports = router;

"public_html/routes/laptop/modules/laptop.js":

var mysql = require('mysql');

var connection = mysql.createConnection(
 {
   host     : 'localhost',
   user     : 'admin',
   password : 'xxxxxxx',
   database : 'database',
 }

);

module.exports = function(req, res){

connection.connect();

var queryString = 'SELECT * FROM laptop';

connection.query(queryString, function(err, rows, fields) {
if (err) throw err;

res.writeHead(200, { 'Content-Type': 'application/json'});
res.end(JSON.stringify(rows));
});

connection.end();
};

I want to keep this modularity even if its look like a bit over complicated, in the future I will need it. So the problem is it's just doesn't working, I think its just a stupid error somewhere, but I don't find it and on the internet there is only simple route examples so I cant use them in this case.

The problem is most likely in your routing.

You're mounting a separate router at /laptop . Within that mounted router you're setting up a /laptop (GET) route on top of that, so the full path would be /laptop/laptop .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM