简体   繁体   中英

Why my RestFul API with express and nodejs crashed everyday?

I have restful api with express and nodejs but this api crashed every time. So.. I have one function for datatime. This function will replace date in the url address everytime to current datetime.. Im not sure but may be when the current date is change with the new current date the API crashed..

I see this error message on the console:

events.js:187
      throw er; // Unhandled 'error' event
      ^

Error: read ECONNRESET
    at TCP.onStreamRead (internal/stream_base_commons.js:201:27)
Emitted 'error' event on Connection instance at:
    at Connection._handleProtocolError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\Connection.js:426:8)
    at Protocol.emit (events.js:210:5)
    at Protocol._delegateError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\protocol\Protocol.js:398:10)
    at Protocol.handleNetworkError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\protocol\Protocol.js:371:10)
    at Connection._handleNetworkError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\Connection.js:421:18)
    at Socket.emit (events.js:210:5)
    at emitErrorNT (internal/streams/destroy.js:92:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  errno: 'ECONNRESET',
  code: 'ECONNRESET',
  syscall: 'read',
  fatal: true
}
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-29T04_48_17_190Z-debug.log

So this is the code for api.. Its very simple.. but I dont know how to fix this error. When I wake up and try to see the data from the API every time the API is crashed.

This is the code from the api:

// 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

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

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

let aladinModel = '';
let 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;

    try {
      const query = `CALL aladin_surfex.Get_mod_cell_values_meteogram_cell('${dateNow}', ${id}, ${daysForward})`;
      con.query(query, function (err, result, fields) {
        if (err) throw err;
        aladinModel = result;

      });
      res.json({ aladinModel })

    } catch (error) { 
      console.log("Error query database!!!");
    }
  });

app.route('/stations')
  .get(function (req, res) {
    // omitted
    res.setHeader('Access-Control-Allow-Origin', '*');
    try {
      const query2 = `SELECT Station,Ime FROM aladin_surfex.stations_cells;`;
      con.query(query2, function (err, result2, fields) {
        if (err) throw err;
        aladinModelStations = result2;
      });
      res.json({ aladinModelStations })
    } catch (error) {
      console.log("Error query database!!!");
    }
  });

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

I try to remove the cashe, to update npm, to restart the computer. But without the result. With nodemon crashed the same.. What can I do ? How can to fix that ?

The error seems to be related to the connection to mysql.

As mysqljs documentation ( https://github.com/mysqljs/mysql#error-handling ):

Note: 'error' events are special in node. If they occur without an attached listener, a stack trace is printed and your process is killed.

You shuld intercept the connection error like this:

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

so you can investigate when and why the error occours and eventually you can recreate the connection when a problem occurs.

  1. Move app.listen to the bottom of the file, after you declare all the routes and connect to the database.

  2. Use app.get('route', function...) (more on that in the Express docs)

  3. Move res.json() inside the callback function for each database query. The result will come back asynchronously so will not be accessible outside the function. If you're new to async and callbacks in Javascript I'd recommend googling them and you'll find a ton of reading materials.

  4. Initialize your variables, eg const aladinModel = ...

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