【问题标题】:ReferenceError: item is not defined nodejsReferenceError:项目未定义nodejs
【发布时间】:2022-01-11 09:43:25
【问题描述】:

我正在尝试使用节点 js 和 express 从 json 文件中获取数据,但是并使用导出定义了方法,但它在我的浏览器上给出了错误

不知道为什么它不起作用,我已经在控制器和路由文件夹中定义了方法

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

这是我的控制器:

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 文件是这样的

[
{
    "_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"
}

]

谢谢。

【问题讨论】:

    标签: javascript node.js json express visual-studio-code


    【解决方案1】:

    问题出在这一行

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

    .map 的第一个参数是一个回调函数。你在做作业

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

    【讨论】:

    • 感谢您弄清楚作业是作业! :P .. 我在谷歌上研究了这个查询,但没有多少答案可用。有时它会给出与实际错误不同的问题和错误跟踪。感谢帮助。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 2013-07-22
    • 2017-04-19
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多