Home > Software design >  ReferenceError: item is not defined nodejs
ReferenceError: item is not defined nodejs

Time:01-11

I am trying to get data from a json file using node js and express but and defined the methods using exports but its is giving error on my browser

not sure why it is not working , i have defined the method in controller and Routes folder

ReferenceError: item is not defined
at exports.getCityList (C:\Users\acer\Documents\EDUREKA\Assignments\Assignment 5\Controllers\City.js:4:36)

here is my controller:

const City = require('../Models/City.json');

exports.getCityList = (req, res) => {
const result = City.map(item = item.name);
res.status(200).json({
    message: "City List loaded successfully",
    city: result
})

}

routes.js

    const express = require('express')

var CityListController = require('../Controllers/City')

const router = express.Router();

router.get('/getCityList',CityListController.getCityList);

module.exports = router;

app.js

const express = require('express');
const bodyParser = require('body-parser');
const router = require('./Routes/routes');
const hostname = "localhost";
const port = "8055";

const app = express();

app.use(bodyParser.json());

 // CORS
app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods','GET,POST,PUT,PATCH,DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
 });

   app.use('/', router);
  app.listen(port,hostname, () => {
 console.log('Server is running on http://${hostname}:${port}');
  })

City.json file goes like this

[
{
    "_id": "1",
    "name": "ShalimarBhagh, Delhi",
    "city_id": "1",
    "location_id": "1",
    "country_name": "India"
},
{
    "_id": "2",
    "name": "Janpat, Delhi",
    "city_id": "1",
    "location_id": "2",
    "country_name": "India"
}

]

thanks.

CodePudding user response:

Problem is with this this line

const result = City.map(item = item.name);

the first argument of .map is a callback function. You are doing an assignment

const result = City.map(item => item.name);
  •  Tags:  
  • Related