Home > Software engineering >  Why this simple export is giving me error in nodejs?
Why this simple export is giving me error in nodejs?

Time:11-13

I got this example product js file and i am exporting it and using it in the node routes

let products = [
    {
      _id: "1",
      name: "Airpods Wireless Bluetooth Headphones",
    },
    {
      _id: "2",
      name: "iPhone 11 Pro 256GB Memory",
    },
    {
      _id: "3",
      name: "Cannon EOS 80D DSLR Camera",
    },
  ];
  
  export default products

and i am getting that data in the server.js like this

const products = require('./data/products')

const app = express()

app.get('/', (req, res) => {
    res.json('api running')
})

app.get('/api/products', (req, res) => {
    res.json(products)
})


app.get("/api/products/:id", (req, res) => {
    const product = products.filter(p => p._id === req.params.id);
     res.json(product);
});

but whenever i try to run the server i got this error Unexpected token 'export'. Why this simple export is giving me error?

CodePudding user response:

You can use common js module syntax instead of es6 module syntax for exporting products:

module.exports = products;
  • Related