-1

I'm trying to create a GET request handler in Express.js like so:

// import files and packages up here

const express = require('./data.json');
var app = express();
var morgan = require ('morgan')
const port = 3000;
console.log(express)

// create your express server below

// add your routes and middleware below

app.get('/', function (req, res, next) {
    res.writeHead(200)
    res.send('USER')
    console.log(express)
})

// export the express application
module.exports = app;

But it's not working, so when I send a GET request, nothing happens.

What's going on?

Danziger
  • 19,628
  • 4
  • 53
  • 83
junior
  • 67
  • 9

1 Answers1

1

First, you are not even requiring express, you are requiring a JSON file, so you should change that first line to:

const express = require('express');

Then, you need to call app.listen once you are done setting up your middleware, which you might be doing in a different file, but it's worth mentioning it.

So, all together with a few other small changes:

// Why?
// const express = require('./data.json');

// It should be like this instead:
const express = require('express');

// And if you want to require a JSON file anyway to send it back:
const data = require('./data.json');

// Require morgan:
const morgan = require('morgan')

// Create the express app:
const app = express();

// Use morgan's middleware in your express app:
app.use(morgan('combined'));

// Define the port to run the server at:
const port = 3000;

// Define your GET / route:
app.get('/', (req, res, next) => {
    // Send status code + text message:
    res.status(200).send('USER');

    // Or if you prefer to send JSON data:
    // res.status(200).json(data);
});

// Start listening on that port:
app.listen(port, () => console.log(`App listening on port ${ port }!`));

If you run this with node <filename>.js after installing all the dependencies, you should see a message like App listening on port 3000! and then morgan will log a message for every incoming request automatically.

Note you can export your app instead of calling app.listen(...) at the end of the file with module.exports = app, but in that case you need to import that somewhere else (maybe you have a server.js file or something like that) and then call app.listen(...) there.

Danziger
  • 19,628
  • 4
  • 53
  • 83
  • The reason I have ( const express = require('./data.json') because I need to grab the data thats in this file and display it on the webpage. I thought using require(data.json) would work – junior Dec 02 '18 at 20:05
  • Yes, you are right, but that's a different thing. You should then do something like `const data = require('./data.json')`, but still need to require `express`. Take a look at this: https://stackoverflow.com/questions/44849082/sending-a-json-file-to-express-server-using-js – Danziger Dec 02 '18 at 22:09
  • Your advice is very helpful! I'm new to programming it's my first week doing working on node – junior Dec 02 '18 at 23:46