Encountering Issue in NodeJS+Express : 'Failed to retrieve /...'

I have been developing an API for restaurants and have created the corresponding controller and model as detailed below.

Controller (restaurantData.js)

const restaurantData = require('../Models/restaurantData');

exports.getRestaurantData = (req, res) => {
    console.log(req.params.city_id.toString())
    restaurantData.find({
        city_id: req.params.city_id.toString()
    }).then(result => {
        res.status(200).json({
            message: "Restaurant Data",
            restaurants: result
        });
    }).catch(error => {
        res.status(500).json({
            message: error
        });
    });
}

Model (restaurantData.js)

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const restaurantSchema = new Schema({
    _id: {
        type: Number,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    city_name:{
        type: String,
        required: true
    },
    city_id: {
        type: String,
        required: true
    },
    location_id: {
        type: Number,
        required: true
    },
    area: {
        type: Number,
        required: true
    },
    locality:{
        type: String,
        required: true
    },
    thumb: {
        type: String,
        required: true
    },
    cost:{
        type: Number,
        required: true
    },
    address:{
        type: String,
        required: true
    },
    mealtype:{
        type: Number,
        required: true
    },
    name:{
        type: String,
            required: true
        },    
    cuisine:{
        type: Number,
        required: true
    },
    type:{
        type: Array,
        required: true
    },
    Cuisine:{
        type: Array,
        required: true
    }
});

module.exports = mongoose.model('restaurantData', restaurantSchema, 'restaurantData');

router.js

const express = require('express');
const restaurantController = require('../Controllers/restaurantData');

const router = express.Router();

router.get('/restaurantData/:cityID',restaurantController.getRestaurantData);

module.exports = router;

app.js

const express = require('express');
const bodyparser = require('body-parser');
const mongoose = require('mongoose');

const apiRouter = require('./Routes/router');

const port = 4005;
const app = express();

app.use(bodyparser.json());

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

app.use('/api', apiRouter);

mongoose.connect(
    'mongodb://127.0.0.1:27017/sampleRestaurant',
    { useNewUrlParser: true, useUnifiedTopology: true }
).then(success => {
    console.log('Connected to MongoDB');

    app.listen(port, () => {
        console.log(`Server started at port ${port}`);
    });

}).catch(error => {
    console.log(error);
});

When testing on Postman, I encountered the error message

"Cannot GET /api/restaurantData"
. Any suggestions on how to resolve this issue would be greatly appreciated.

Answer №1

Upon reviewing your model, I came across an error in which you're requesting

req.params.city_id.toString()

This conversion to a string is neither correct nor necessary.

Instead, consider using the following:

const restaurantData = require('../Models/restaurantData');

exports.getRestaurantData = (req, res) => {
    const cityId = req.params.cityID;
    console.log(cityId)
    restaurantData.find({
        city_id: cityId
    }).then(result => {
        res.status(200).json({
            message: "Restaurant Data",
            restaurants: result
        });
    }).catch(error => {
        res.status(500).json({
            message: error
        });
    });
}

The issue lies in your requirement of the parameter city_id instead of cityID as used in your route:

router.get('/restaurantData/:cityID',restaurantController.getRestaurantData);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Establish a fresh MongoDB collection containing a JSON structure within its schema

I've been working on creating a new collection with MongoDB recently. Everything was going smoothly until I started encountering issues when trying to send parameters containing JSON data. Here is the schema that I created: const partySchema = mongoo ...

Guide to using get() and res.sendFile() function to redirect webpages

Why is the page not redirecting properly? In my index.html file, I have this script: $.get( "/loginPage", function( data ) {}); The purpose of this script is to check if a user is logged in. If they are, it should redirect them to the lobbyPage. This is ...

Tips for generating and invoking a promise within NodeJS

I have been attempting to access Firestore using a function I created that includes a collection variable. var fetchDataFromFirestore = function(collection, doc){ return promise = new Promise(function(resolve,reject){ //If doc param is null Quer ...

Ways to resolve the issue of npm being unable to globally install typescript

While trying to globally install TypeScript using npm sudo npm install -g typescript An error occurs during the installation process with the following message: ENOENT: no such file or directory, chmod '/usr/local/lib/node_modules/typescript/bin/ ...

What sets response.setHeader apart from response.writeHead?

When it comes to sending a JSON response from my Nodejs server in my application, I have discovered two different methods. However, I am unsure about the distinctions between them. The first method involves var json = JSON.stringify(result.rows); respons ...

Using axios to make a request from a server to itself

I'm facing an issue where I am attempting to send a request from the server to the same server using axios as a PUT method. Here is an example of what I have tried: await axios({ url: `http://localhost:4000${url}`, method: requestType, ...

Unable to load Vash template

Currently, I am working with Vash as my chosen template engine. What I'm trying to achieve is to have the header and footer stored in separate files that can then be included in the layout.vash file. layout.vash <body> <header> ...

Encountering a Troubleshooting Issue with ArcGIS JS API 4.7 and N

Recently, I have been attempting to set up ArcGIS JS API 4.7 using npm for a Vue.JS project. However, when I execute the command npm install arcgis-js-api I encounter an error with NPM: npm ERR! code E404 npm ERR! 404 Not Found: @dojo/i18n@~0.6.0 Althou ...

Leveraging client API callback variables within a Node.js backend system

If I send a request on the client side using the code snippet below public/foo.js function bar() { fetch('https://api.github.com/') .then(response => response.json()) .then(data => { console.log(data) }) .catch( ...

How to retrieve the second query result using Firestore cloud function

I am facing an issue with my on-create cloud function. I need to transfer data from one container to another. The first query appears to be running fine as I can check the data, but I'm encountering a problem with the second query where I attempt to a ...

Authenticate yourself as a user or an organization on mongodb

I am currently developing an application that requires user registration and login, as well as organization registration and login. I have implemented the use of Node.js Passport with a local strategy for authentication. While I have successfully created t ...

The Express/Node server keeps crashing unexpectedly due to an events.js ECONNRESET error

Currently, I am in the process of developing an application using Node.js, Express, and Mongoose. For my development environment, I have opted for Cloud9. Initially, I used express generator to set up the foundation of my app and have since been making inc ...

Register when a user signs up or buys a product from stripe's subscription service

Currently, I am in the process of developing an application that allows public users to access a pricing page and choose a plan (utilizing stripe for subscription payments). Once a user selects a plan and proceeds to checkout, my aim is to have them redi ...

Set up Renovate Bot to utilize a personalized NodeJS image options

Utilizing a self-hosted Renovate Bot instance within an air-gapped GitLab environment to manage NodeJS module updates has presented some challenges for me. Despite thoroughly reviewing the documentation, I'm unclear on how to configure the bot to prev ...

How can I include already installed packages in the 'dependencies' and 'devDependencies' sections of my package.json file after deleting the original package.json?

Contemplating the multitude of packages I added to my Project using npm, I inadvertently deleted my package.json file while tidying up. To remedy this, I executed the command nmp init to generate a new package.json file. The resulting package.json file a ...

Copying Objects in JavaScript Using Deep Cloning

My current project involves using Nodejs to create a deep copy of an object generated by Squel, a query building library. The main dilemma lies in how to replicate the exact filteredQuery variable. The object is initialized with: filteredQuery = squel.sel ...

Updating a specific subfield of a document in Mongoose using NodeJS with Express

I have set up the following schemas in my Node server SCHEMAS const mongoose = require('mongoose'); const Schema = mongoose.Schema; const dataSchema = new Schema({ time: Date, value: String }); const nodeSchema = new Schema({ name: ...

Can you explain the distinction between req.query and req.body in Express?

Can you explain the difference between req.query and req.body? In the code snippet below, req.query is being used. What would happen if we replaced it with req.body instead? The following function is triggered by the $resource get function. It checks for ...

What is the reason behind being limited to sending only 5 requests if I fail to heed the data event?

I've come across some related questions while researching this topic, such as Why is node.js only processing six requests at a time?. However, I am still struggling to fully grasp the specifics. Below is a breakdown of my scenario: Firstly, let&apos ...

Show customized/designed text - react

I'm currently in the process of developing a web application specifically for sharing announcements. One of the features I have implemented is a rich text editor, allowing users to format their text by making it bold, underlined, and more. The text en ...