0

This code works:

const express = require('express');
const Router = express.Router();

Router.get('/hello-world', (req, res, next) => {                                     
    res.send("hello world!"); //works great                   
});

But this code doesn't:

const {Router} = require('express');

Router.get('/hello-world', (req, res, next) => {                                     
    res.send("hello world!"); // :( doesnt work                  
});

What am I misunderstanding about destructuring? Thanks

hamncheez
  • 709
  • 12
  • 22
  • 1
    Object Destructuring wont work as Router is a function. If the require module had a property Router then it can be accessed in the way you have coded. – Monica Acha Mar 02 '19 at 15:10

1 Answers1

3

You would still need to call the function:

const {Router} = require('express');
Router().get('/hello-world', (req, res, next) => {
//    ^^
    res.send("hello world!"); // :( doesnt work                  
});

What am I misunderstanding about destructuring?

The code

const {Router} = require('express');

is equivalent to

const temp = require('express');
const Router = temp.Router;

but you were doing

const express = require('express');
const Router = express.Router();
//                           ^^
Bergi
  • 630,263
  • 148
  • 957
  • 1,375