Having trouble with sending a POST request using Rest Client, Express, and Node.js?

const express = require('express')
const router = express.Router()
const flightMethods = require("../model/users")
//Setting up routing based on requirements
router.post('/bookFlight', (req, res, err, next) => {
    let flightBookingObj = JSON.parse(req.body);
    flightMethods.bookFlight(flightBookingObj).then((id) => {
       return res.status(201).json({"message": `Flight booking successful with ID ${id}`})
    })
    if(err){
       return next(err);
    }

})
module.exports = router;

Router.js File Is this the correct way to send JSON data with a REST client for an application/json object.

{"customerId": "P1001",
"bookingId": 2001,
 "noOfTickets": 3,
 "bookingCost": 1800,
 "flightId":undefined
 }

Defined FlightBookingObj as:

class FlightBooking {
    constructor(obj) {
        this.customerId = obj.customerId;
        this.bookingId = obj.bookingId;
        this.noOfTickets = obj.noOfTickets;
        this.bookingCost = obj.bookingCost;
        this.flightId = obj.flightId;
    }
}

Error occurs when making a POST request to this route using the REST Client.

Answer №1

Check out this code snippet for handling Post requests in NodeJs using Express

app.js

    const express = require('express');
    const routes = require('./routes.js');
    const app = express();
    
    app.use('/', routes);
    
    const server = app.listen(3000, function(){
        console.log('Server is running on port 3000');
    });

routes.js

    const express = require('express');
    const router = express.Router();
    
    router.route('/bookFlight').post(function(req, res, next) {
        const flightBookingObj = req.body.flight;
        // Assuming the post request includes an object named flight in its body
    });

    module.exports = router;

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

Unique browsing key

Is there a specific identifier that can uniquely represent the browser you are currently using? I have two applications logged in through ApiGateWay, and I need to determine whether they are both running on the same browser. Therefore, I require a unique ...

After calling sequelize.addModels, a Typescript simple application abruptly halts without providing any error messages

My experience with Typescript is relatively new, and I am completely unfamiliar with Sequelize. Currently, I have only made changes to the postgres config in the .config/config file to add the dev db configuration: export const config = { "dev" ...

Is MongoClient establishing 22 connections while the poolSize is configured to 1?

Having encountered a problem with an excessive number of connections open to my mongod, I decided to create a new database for clean testing. To limit the connections, I set the poolSize to 1 in the following manner: MongoClient.connect( url, { server: ...

Choosing between creating a class with a shared instance or not

I'm curious if my class is shared across instances: for example, I have a route that looks like this: /student/:id When this route triggers the controller (simplified version): module.exports = RecalculateStudents; const recalculateActiveStudent ...

Wrong skill receives request instead of intended Alexa skill

Unexpectedly, the Alexa simulator has begun sending requests to other skills instead of mine. While I am able to invoke my skill and receive a response, any intent I try to use results in an audio-only response. Upon checking the server logs (hosted on Her ...

Proper protocol for ensuring API database tables are synchronized

This is my first experience developing an application independently, handling the back-end, front-end, and design. I would appreciate some advice on structuring my back-end. Let's consider a scenario where there are tables for Users, Jobs, and Applic ...

Utilizing Environment Variables Across Multiple Files in Node.js with the Help of the dotenv Package

I am currently developing a basic application that utilizes the Google Maps API and Darksky API. To keep my API keys secure, I have implemented dotenv for key management. I have successfully integrated dotenv in my main file (app.js), but now I need to a ...

Encountering issues with the Sequelize Model.prototype.(customFunction) feature malfunctioning

While attempting to define a customFunction within the Sequelize model, I encountered an error: TypeError: user.getJWT is not a function at User.create.then (/projects/test/a/app/controllers/UserController.js:22:29) Below is the code snippet from ...

Firebase Cloud Functions cycle through a nested node within the database

Recently, I began diving into firebase Functions and navigating the node.js environment. I'm looking for guidance on how to effectively iterate through a child node in order to obtain the child values. Can anyone provide assistance with this? ...

The issue with nodejs multer is that it is successfully receiving the req.file but failing to upload it

multer.js var path = require("path"), multer = require("multer"); const storage = multer.diskStorage({ destination: function(req, file, next){ next(null, '../public/imgs/'); return; }, filename: function(req, file, ...

Issue with updating user information in KeystoneJS: name, email, password, and more

Recently diving into keystone js, I am currently working on a web app that includes a user dashboard. My goal is to utilize the updateItem method on a user item that has already been indexed, searched, or queried in the first parameter of the function. // ...

Exploring the world of Node.js with fs, path, and the

I am facing an issue with the readdirSync function in my application. I need to access a specific folder located at the root of my app. development --allure ----allure-result --myapproot ----myapp.js The folder I want to read is allure-results, and to d ...

Issues arise when attempting to utilize Node.js Socket.io on localhost, as the calls are ineffective in performing logging, emitting, generating errors, or executing any other actions. It has been noted that

I am in the process of developing a real-time socket.io application using Angular and Node, following the instructions provided here. I have set up the server and client connection, but unfortunately, the connection is not being established. Server Code: ...

"Optimizing Performance: Discovering Effective Data Caching

As a developer, I have created two functions - one called Get to fetch data by id from the database and cache it, and another called POST to update data in the database. However, I am facing an issue where I need to cache after both the get and update oper ...

Facing issues with nodejs socket.io communication on a local network

I've been working on setting up a chat feature for my website, but I'm running into issues getting socket.io to function properly on my local network (it works fine for localhost but not when accessed from another machine). Here is the server-sid ...

Node.js request.url is returning incomplete URL

I am currently testing out the code snippet provided in a beginner's book on Node.js. var http = require("http"); var url = require("url"); function onRequest(request, response) { console.log("request URL is: " + request.url); var pathName ...

Encountering issue with npm twigjs while compiling template containing twig features

Recently, I created a boilerplate for utilizing twig with webpack and nodejs. If you're interested, you can access it here: My Twig boilerplate While the boilerplate works fine for basic tasks like iteration and if statements, I encountered an issue ...

Issue with Node.js: npm is failing to install now

I'm facing an issue while trying to install a module using npm as it keeps returning errors. Even when attempting to install the same module, like in this example: npm install socket.io The following error is shown: npm ERR! TypeError: Cannot call ...

Looking for a way to sort through data using the current time as a filter

In my possession is an object presented below: const user = { id: 3, name: "Clark Kent", mobileNumber: "1234567892", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385d40595548545d674d4b ...

Having trouble connecting to Google Cloud SQL database from my App Engine application

Last week I embarked on setting up Google Cloud for a NodeJS API along with a Cloud SQL database. While everything seems to be functioning smoothly, I am encountering difficulties in accessing my Cloud SQL database. The authorization settings for the datab ...