Scary
Scary

Reputation: 91

node.js ReferenceError: server is not defined

The below code is from server.js, it's causing my server to crash with Error:

ReferenceError: server is not defined at Object. (C:\xampp\htdocs\api\src\server.js:17:18) at Module._compile (module.js:571:32) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) at Module.runMain (module.js:605:10) at run (bootstrap_node.js:418:7) at startup (bootstrap_node.js:139:9) at bootstrap_node.js:533:3

var express = require('express');
var body_parser = require('body-parser');
var app = express()

// Port config
var port = 3000;

app.use(body_parser.json());

// Use prefix of api
app.use('/api', require('../routes/api.js')(express));

app.listen(port, function(){
  console.log('Server Active on', port);
});

module.exports = server;

Mocha testing (__app.js)

var request = require('supertest');

describe('API', function() {

var server;

beforeEach(function () {
  server = require('../src/server.js');
});

afterEach(function () {
  server.close();
});

it('/ should return specified object.', function (done) {
  request(server)
    .get('/api/')
    .set('Accept', 'application/json')
    .expect('Content-Type', /json/)
    .expect(200, {"hello": "world"}, done);
});

it('/status should return specified healthy:true', function (done) {
  request(server)
    .get('/api/status')
    .set('Accept', 'application/json')
    .expect('Content-Type', /json/)
    .expect(200, {"healthy": true}, done);
});

it('/user/id should return user object with id.', function (done) {
  var fakeUserID = 374;
  request(server)
    .get('/api/user/347' + fakeUserID)
    .set('Accept', 'application/json')
    .expect('Content-Type', /json/)
    .expect(200, {user: {id: fakeUserID}}, done);
  });
});

Am I missing a package? I'm watching a video with the same exact code and it doesn't crash the server.

Upvotes: 0

Views: 23317

Answers (3)

Awais Zahid
Awais Zahid

Reputation: 39

You should try this:

const server = app.listen(port, function(){
  console.log('Server Active on', port);
});

Upvotes: 0

Paul Fitzgerald
Paul Fitzgerald

Reputation: 12129

You want to export the app. No variable called server exists

module.exports = app;

You can then import the app elsewhere in your project using require

Upvotes: 2

cybersam
cybersam

Reputation: 66999

server is not defined anywhere. As a guess, you probably want to change the last line to:

module.exports = app;

Upvotes: 1

Related Questions