撰寫簡單的應用程式從 nodejs 服務器獲取資料。
但似乎無法在瀏覽器和 POSTMAN 中獲取檔案。我曾多次嘗試檢查網址,但無濟于事。
這是我的檔案:
應用程式.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}');
})
路由.js
const express = require('express')
var CityListController = require('../Controllers/City')
var RestaurantCityController = require('../Controllers/Restaurants')
var MenuController = require('../Controllers/Menu')
const router = express.Router();
router.get('/getCityList',CityListController.getCityList);
router.get('/getRestaurantsByCity/:cityname', RestaurantCityController.getRestaurantsByCity);
router.get('/getMenu', MenuController.getMenu);
module.exports = router;
選單.js
const mealtypes = require('../Models/menu.json');
exports.getMenu = (req, res) => {
const resultname = mealtypes.map(items => items.name)
res.status(200).json({
message: "widgets data fetched successfully",
name : resultname
})
}
menu.json 是這樣的
[
{
"_id": "1",
"name": "Breakfast",
"content": "Start your day with exclusive breakfast options",
"image": "assets/breakfast.png"
},
{
"_id": "2",
"name": "Lunch",
"content": "Start your day with exclusive breakfast options",
"image": "assets/lunch.png"
}
]
錯誤是 無法獲取 /getMenu
不確定錯誤在哪里,因為它是一條簡單的路線..不確定缺少什么。謝謝
uj5u.com熱心網友回復:
該錯誤Cannot GET /來自嘗試訪問http://localhost:8055
生成它是因為沒有
http://localhost:8055/使用/express中的路徑的根目錄的路由。這是一條
http://localhost:8055/getMenu運行良好的路線。
測驗代碼
const express = require('express');
const getMenu = (req,res) => res.status(200).json({ test_data: "test_data"});
const router = express.Router();
router.get('/getMenu', getMenu);
const hostname = "localhost";
const port = "8055";
const app = express();
app.use('/', router);
app.listen(port,hostname, () => {
console.log(`Server is running on http://${hostname}:${port}`);
})
uj5u.com熱心網友回復:
您的代碼應該與 http://localhost:8055/getMenu 一起使用。我復制了您的代碼并為我作業鏈接到 repo。
{
"message": "widgets data fetched successfully",
"name": [
"Breakfast",
"Lunch"
]
}
uj5u.com熱心網友回復:
似乎出現了技術錯誤。
現在作業正常。我剛剛重新啟動了 nodemon app.js。
它現在正在作業。一直在嘗試修復網址。
謝謝大家的幫助
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/408289.html
標籤:
上一篇:等待回圈結束?
