简体   繁体   中英

NodeJS Firebase App crash on Invalid JSON

This is my NodeJS application. I've commented out some parts to narrow down the issue.

const functions = require('firebase-functions');
const express = require('express');
// const path = require('path');
// const bodyParser = require('body-parser');
const app = express();
// const gameAPI = require('./routes/apiv1');
const startTime = Date.now();

Error.stackTraceLimit = Infinity;
console.log("Server Started");

// app.use('/node_modules',express.static(path.join(__dirname, 'node_modules')));
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: true }));
app.use((err, req, res, next) => {
    res.status(500).send();
});

// app.use('/v1.0', gameAPI);

app.get('/', (req, res)=>{
    res.send(`App started ${(Date.now() - startTime)/1000}s ago`);
});

exports.app = functions.https.onRequest(app);

when I send an invalid JSON

{
    "ign":"XX"
    "allies": "5"
}

The application crash.

[11:21:31]{}firebase-test:sulochana$ firebase serve --only functions,hosting
✔  functions: Using node@8 from host.
✔  functions: Emulator started at http://localhost:5001
i  functions: Watching "/home/sulochana/Documents/firebase-test/functions" for Cloud Functions...
i  hosting: Serving hosting files from: public
✔  hosting: Local server: http://localhost:5000
>  Server Started
✔  functions[app]: http function initialized (http://localhost:5001/scrim-engine/us-central1/app).
[hosting] Rewriting /v1.0/dota/queue to http://localhost:5001/scrim-engine/us-central1/app for local Function app
>  Server Started
i  functions: Beginning execution of "app"
>  SyntaxError: Unexpected string in JSON at position 15
>      at JSON.parse (<anonymous>)
>      at parse (/usr/lib/node_modules/firebase-tools/node_modules/body-parser/lib/types/json.js:89:19)
>      at /usr/lib/node_modules/firebase-tools/node_modules/body-parser/lib/read.js:121:18
>      at invokeCallback (/usr/lib/node_modules/firebase-tools/node_modules/raw-body/index.js:224:16)
>      at done (/usr/lib/node_modules/firebase-tools/node_modules/raw-body/index.js:213:7)
>      at IncomingMessage.onEnd (/usr/lib/node_modules/firebase-tools/node_modules/raw-body/index.js:273:7)
>      at emitNone (events.js:111:20)
>      at IncomingMessage.emit (events.js:208:7)
>      at endReadableNT (_stream_readable.js:1064:12)
>      at _combinedTickCallback (internal/process/next_tick.js:139:11)

How to handle this exception. This will allow external users to crash the application

You have to determine where the JSON.parse() method is being invoked and then precede it with a test for whether the JSON is valid before trying to use the parsed output. For example:

const isValidJson = jsonString => {
  try {
    JSON.parse(jsonString)
    return true
  } catch(err) {
    return false
  }
}

if (isValidJson(jsonString)) JSON.parse(jsonString)

The likeliest culprit for where this parsing is happening appears to be in your game API, since it seems to be handling your app's routes.

As a developer, you need to validate the input data before the process.

Validate JSON

    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }

Restart Server On Unexpected Crashes

And also, You can use some packages like forever , to restart your server automatically when it crash..

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