我正在嘗試使用節點 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
})
}
路由.js
const express = require('express')
var CityListController = require('../Controllers/City')
const router = express.Router();
router.get('/getCityList',CityListController.getCityList);
module.exports = router;
應用程式.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"
}
]
謝謝。
uj5u.com熱心網友回復:
問題在于這條線
const result = City.map(item = item.name);
的第一個引數.map是一個回呼函式。你在做作業
const result = City.map(item => item.name);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/408126.html
標籤:
下一篇:如何確定指標指向的地址?(理論)
