Node.js-Express Help: why do the changes I make in the code don't take effect when I run it?

This is very odd. Any idea why that could happen?
I save the files (Atom) and do ‘npm start’ again.

I think we’d really need to see the code, and what the expected behavior is versus what you are coding.

I assume you are testing endpoints? Is is possible you have more than one server running and you are testing the old one?

I’ll try to paste only the relevant parts and not the trivial code:

app.js:

var shortenerRouter = require('./routes/index');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', shortenerRouter);

routes/index.js:

const shortenerRouter = express.Router();

shortenerRouter.use(bodyParser.json());

shortenerRouter.route('/')
.get(function(req, res, next) {
  console.log(".get")
  //res.render('index', { title: 'Express' });
  res.json({user: "moi"})
})

It should return “moi” but instead it displays the static index page.

OK, I wasn’t able to get what you have working. When I initialize an npm package, change your files to:

App.js

const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');

var shortenerRouter = require('./routes/index');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', shortenerRouter);

const PORT = 8080;

app.listen(PORT)
  .on('listening', () => {
    console.clear();
    console.log('server listening on port:', PORT);
  })
  .on('error', (err) => {
    console.error('### error opening port:', PORT);
    console.error(err);
  });

and index.js

const express = require('express');
const bodyParser = require('body-parser');
const shortenerRouter = express.Router();

shortenerRouter.route('/')
.get(function(req, res, next) {
  res.json({user: "hey"})
})

module.exports = shortenerRouter;

and install the relevant packages with something like:
npm i -S express body-parser morgan cookie-parser

then it works. I can change the return value in the route, restart the server, and get the new data by putting http://localhost:8080/ in the browser address.

You were missing some of the package imports. I had to guess which logger you were using, and I had to export your router - but with that it works.

Instead of using node to run your server, I might suggest installing the very common and helpful nodemon:

npm install -g nodemon

Then you run your app:

nodemon App.js

and it will restart the server for you when you make changes.

2 Likes