2

Currently I'm running a node js backend with express to access the mysql database from the client. Now I'm refactoring my code to put the "fat" things from the client also to the nodejs backend. My first idea is to keep the express route like:

ModuleA:

router.get('/getitem/:code',(req, res) => {
let sql = `SELECT * FROM xyz WHERE CODE = ${req.params.code}`;
let query = db.query(sql, (err, result) =>{
  if(err == null){
    console.log(result);
    res.send(result);
  }else{
    console.log("Error by getting item from db: " + err);
    throw err;
  }
 });
});

And access it via http request by a other module if needed:

function geodataByLocationcode(locationcode){
 request({
  method: 'GET',
  url: "http://" + server_connection.host + ":" + server_connection.port + '/getitem/' + locationcode,
  headers: {
    "Content-Type": "application/json"
  }
 },function(error, response, body){
 ....
 }

But is this the best method to do this? Or would it be better to access the db in a more direct way since the request now also comes from the backend?

3
  • Well In my honest opinion have database access in our controllers is not a good approach... why not have a service module to handle database queries? Because having db dependencies in your controller it will make hard to unit test... Commented Oct 10, 2017 at 13:44
  • do you have any examples/tutorials for this? Commented Oct 10, 2017 at 13:46
  • Just a big security warning! Don't EVER send valyes from the request into the database query like you are doing in the above code with req.params.code. Users can easily send something like "1; DELETE FROM users;" Commented Apr 18, 2021 at 0:33

1 Answer 1

7

You can find a good example how to use MySql and Node.js using native drivers (without any query builder like knex or ORM like bookshelf).

Dependencies:

  • expressjs 4.x
  • mysql2

expressjs 4.x

The core concepts are:

Example: https://github.com/Talento90/organization-api/tree/master/organizations-api/src

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.