1

i'm programming in Atom using a server javascript file, JSON data and node server!

 var fs = require('fs');
 var dataP = fs.readFileSync('database.json');
 var data = JSON.parse(dataP);
 var express = require('express');
 var app = express();
 var server = app.listen(3000);

 app.use(express('website'));
 app.get('/check/:input', addInput);

 function addInput(request, response){
 var inputData = request.params.input;
 if(!inputData){
          response.send("Error: no input was found");
      }
 }

So I have the terminal running my server from entering nodemon server.js When I test the url code @ localhost:3000/check it won't catch the error message that I wrote Error: no input was found which I find is strange since it's a null input if I'm assuming correctly. I also tried to change the if statement and added:

 if(!data && data == null)

 //Also tried

 if(!data || data == null)

None of these statements seems to be able to catch the error. The message I get in return from the server is: Cannot GET /check/

 //if I add a ? at the end of input like this

 app.get('/check/:input?');

I'll get a message: Internal Server Error

Would there be another solution to handle catching errors? I tried to debug this but it would skip the app.get line which I'm then unable to watch the variables to check.

Zulu
  • 81
  • 3
  • 10

1 Answers1

0

I couldn't find it in the docs, but after several attempts, I was able to get it to work using the route /check/:input*? (note the asterisk and question mark).

Here is my code:

const express = require('express');
const app = express();
const server = app.listen(3000);

app.use(express('website'));

app.get('/check/:input*?', (req, res) => {
    const { input } = req.params;
    if (!input) {
        res.send('Value not specified!');
    } else {
        res.send(`Value was "${input}", woohoo!`);
    }
});
  • Visiting /check prints Value was not specified
  • Visiting /check/winning prints Value was "winning", woohoo!

I tested with node 8.4.0 and express 4.15.4 in a new project. The code above should work in node 6.7+ and express 4.0+ as far as I can tell.

See this answer which addresses the same problem.

styfle
  • 22,361
  • 27
  • 86
  • 128