简体   繁体   中英

RestFul API with express and node.js crashed everytime how to fix that?

Every time my API crashed one two times in 24 hours.

I see this error:

ECONNRESET
C:\Users\Admin\Desktop\node-express 1.0.1\server.js:50
        if (err) throw err;
                 ^

Error: Cannot enqueue Query after fatal error.
    at Protocol._validateEnqueue (C:\Users\Admin\Desktop\node-express 1.0.1\node_modules\mysql\lib\protocol\Protocol.js:212:16)
    at Protocol._enqueue (C:\Users\Admin\Desktop\node-express 1.0.1\node_modules\mysql\lib\protocol\Protocol.js:138:13)
    at Connection.query (C:\Users\Admin\Desktop\node-express 1.0.1\node_modules\mysql\lib\Connection.js:201:25)
    at C:\Users\Admin\Desktop\node-express 1.0.1\server.js:49:11
    at Layer.handle [as handle_request] (C:\Users\Admin\Desktop\node-express 1.0.1\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Admin\Desktop\node-express 1.0.1\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Admin\Desktop\node-express 1.0.1\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Admin\Desktop\node-express 1.0.1\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Admin\Desktop\node-express 1.0.1\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\Admin\Desktop\node-express 1.0.1\node_modules\express\lib\router\index.js:335:12) {
  code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR',
  fatal: false
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! express-api@1.0.0 start: `node server.js`
npm ERR!
npm ERR! Failed at the express-api@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Admin\AppData\Roaming\npm-cache\_logs\2019-12-31T06_50_16_476Z-debug.log
PS C:\Users\Admin\Desktop\node-express 1.0.1> npm start

> express-api@1.0.0 start C:\Users\Admin\Desktop\node-express 1.0.1
> node server.js

Im not sure what exactly happend if this statemant on line 50;

if (err) throw err;
        aladinModel = result;
        res.json({ aladinModel })
      });
    } catch (error) { 
      console.log("Error query database!!!");
    }

My full code:

   // Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')

app.use(cors())

// Server port
var HTTP_PORT = 8000

var con = mysql.createConnection({
  host: "192.168.0.1",
  port: "1234",
  user: "username",
  password: "pass"
});

var aladinModel = '';
var aladinModelStations = '';

function formatDate(date) {
  var d = new Date(date),
      month = '' + (d.getMonth() + 1),
      day = '' + d.getDate(),
      year = d.getFullYear();

  if (month.length < 2) 
      month = '0' + month;
  if (day.length < 2) 
      day = '0' + day;

  return [year, month, day].join('-');
}

var dateNow = formatDate(Date());

app.route('/')
  .get(function (req, res) {
    // omitted
    res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
    //const date = req.query.date;
    const id = req.query.id;
    const daysForward = req.query.daysForward;

      const query = `CALL aladin_surfex.Get_mod_cell_values_meteogram_cell('${dateNow}', ${id}, ${daysForward})`;
      con.query(query, function (err, result, fields) {
        if (err) 
        return res.status(500).json({ error: "Internal server error"})
        aladinModel = result;
        res.json({ aladinModel })
      });
  });

app.route('/stations')
  .get(function (req, res) {
    // omitted
    res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
    const id2 = req.query.id2;
      const query2 = `SELECT Station,Ime FROM aladin_surfex.stations_cells WHERE Station=${id2}`;
      con.query(query2, function (err, result2, fields) {
        if (err) 
        return res.status(500).json({ error: "Internal server error"})
        res.json({ aladinModelStations })
      });

  });

  // Start server
app.listen(HTTP_PORT, () => {
  console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT))
});

con.on('error', function(err) {
  console.log(err.code); // 'ER_BAD_DB_ERROR'
});

app.use(function (req, res) {
  res.status(404);
});

I updated the code as the person wrote me from the first comment. Can there be a mistake somewhere else. I remove try catch blocks on the routes.

I think I made it so that there would be no possibility of breaking through the website

This can be due to the MySQL connection keeps disconnecting for some reasons. Seems its common issue. You can handle it in two ways. 1. Create an handler function on mongo disconnect and call the same in error handler. It could be something like :

function mongoConnectionHandler(){
con.destroy();
con= mysql.createConnection(//..db config data);
    con.connect(function(err) {
        if(err) {
            console.log(' Error connecting to db', err);
            setTimeout(handleDisconnect, 1000);
        }
    });
}

//Call this under your "if (err) throw err;". 2. Use Pooled MySQL Connections, which is reserving a certain number of connections ready. Use it and release when required:

var pool  = mysql.createPool({
    connectionLimit : 10,
    host : 'example.org',
    user : 'bob',
    password : 'secret',
    database : 'my_db'
});

pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});

More reference : https://github.com/mysqljs/mysql#pooling-connections

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