Troubleshooting the Non-functioning req.value & ip with Node.js - Joi schema

I have implemented a joi schema to validate email and password that are sent as JSON in the request body. Now, I want to add an additional validation for the IP address. However, when I tried to do so, I encountered the following error:

{
    "isJoi": true,
    "name": "ValidationError",
    "details": [
        {
            "message": "\"ip\" is required",
            "path": [
                "ip"
            ],
            "type": "any.required",
            "context": {
                "key": "ip",
                "label": "ip"
            }
        }
    ],
    "_object": {
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d9dac7d0d8d9dcc5c6c0d88587f5d4d7d69bd4c1">[email protected]</a>",
        "password": "kyuser2923?"
    }
}

Here's the joi schema defined in routehelpers.js:

const Joi = require('joi');

module.exports = {
    validateSignup: (schema) => {
        return (req, res, next) => {
            const result = Joi.validate(req.body, schema);
            if (result.error) {
                return res.status(400).json(result.error);
            }

            if (!req.value) { req.value = {}; }
            req.value['body']= result.value;
            next();
        }
    },
    schemas: {
        signupSchema: Joi.object().keys({
            email: Joi.string().email().required(),
            password: Joi.string().required(),
            ip: Joi.string().ip({
              version: [
                'ipv4',
                'ipv6'
              ],
              cidr: 'required'
            }).required()
        })
    }
}

When I try to extract the IP address in my controller using:

const curIP = req.ip;
console.log('IP: '+curIP);

I do get the IP address in the console as follows:

Server running at http://127.0.0.1:4002/
IP: 127.0.0.1

However, how can I validate the requesting server's IP address during the signup process? It seems like the current validation only checks for the "ip" field in req.value.body. How should I modify the validateSignup function to also include the IP address of the requesting server?

Answer №1

It seems that you are attempting to match the ip property in the body, but it is actually a property of the req object.

You can try this alternative solution:

const result = Joi.validate(Object.assign(req.body, { ip: req.ip }), schema);

However, I suggest using a library like proxy-addr for a better approach. This library can accurately extract the client's IP address even if your server is running behind a reverse proxy.

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

Having trouble running the development environment with npm or pnpm due to permission problems

I encounter this issue when running the command without sudo, but everything works fine with elevated permissions. What could be causing this discrepancy? I've searched for similar questions on various platforms and encountered the same problem with b ...

Turning Node.js timestamp into MySQL format

Currently, I am using Node (Express.js) to update a MySQL database with the current date. While it is functional, my code seems to be repetitive. let newDate = new Date(); let yearNow = newDate.getFullYear(); let monthNow = newDate.getMonth(); let dayNow ...

Steps to develop a collaborative NPM package

I am currently in the process of developing an NPM package using Typescript that contains solely my type interfaces. At the moment, my project has the following folder structure: project │ index.ts │ └───types │ restaurant.ts │ ...

The abrupt end of an HTTP connection occurs in a Node.js application deployed on Amazon EC2

I am currently running a REST API on Amazon EC2 using Node.js (Express). During a specific REST call, the client receives a reply of approximately 5MB. However, before the client can fully receive the reply, an error message is displayed: Premature end o ...

Experiencing an ER_CON_COUNT_ERROR is common when the default max pool of Knex.js is exceeded due to an overwhelming

We currently have 30 DigitalOcean droplets, each dedicated to a web CRM user. They all share the same MySQL database using knex.js. However, with a few additional users, we are encountering some errors: "ER_CON_COUNT_ERROR: Too many connections" ...

The server is failing to provide the requested data in JSON format

I am struggling with making a simple API call using Node.js as the backend and React in the frontend. My Node.js file is not returning data in JSON format, and I'm unsure of the reason behind this issue. I need assistance with two main things: Why is ...

Could ffmpeg-concat be set up on a Windows system?

I am interested in utilizing ffmpeg-concat on a Windows server as a CLI. I have attempted to create an executable using nexe and pkg but encountered various errors in the process. As this is my first experience with node.js, I appreciate your patience with ...

SKIPPING OPTIONAL DEPENDENCY: Incompatible platform for [email protected]: specified platform is { "os":"darwin","arch":"any" } but current platform is { "os":"win32","arch":"x64" }

I am having issues with installing Webpack. Despite trying various commands multiple times, such as npm install --no-optional npm install --global webpack npm install --save-dev webpack npm install i -g --save-dev webpack webpack-dev-server npm i -D ...

Tips for verifying the presence of an active session after closing the browser

Here is my situation: When a user logs into the app and then opens another browser window, they are already authenticated thanks to express-session, bypassing the login page. This pattern continues for subsequent browser windows. The issue I am facing no ...

Utilize node.js on your local machine and leverage gulp to monitor any modifications

I recently copied a repository from https://github.com/willianjusten/bootstrap-boilerplate and followed these steps. git clone git://github.com/willianjusten/bootstrap-boilerplate.git new_project cd bootstrap-boilerplate npm install gulp The gulp comman ...

Transmit information to the client-side webpage using Node.js

One of the main reasons I am diving into learning Node.js is because I am intrigued by the concept of having the server send data to the client without the need for constant querying from the client side. While it seems achievable with IM web services, my ...

What is the best way to create a distinct slug using TypeScript and mongoose?

After scouring through numerous modules, I couldn't find one that worked with TypeScript, including mongoose-slug-generator and mongoose-slug-plugin. ...

Obtaining URL with a specific ID through the useEffect hook in Reactjs

I am currently developing a Mernstack application, and within my application I have an Event Model. My goal is to display a single event when it is clicked as a link. The current challenge I am facing is how to utilize the useEffect hook to load a single ...

Ways to send JWT in the request header to an Angular6 application

Managing users and sessions through an external application such as a Web Application Firewall (WAF) The external app sends a JWT with user information in the request header to the Angular6 app The Angular6 app needs to extract the information from the req ...

How can I maintain form data submission to the server without triggering a redirect?

I am currently in the process of developing a web application that utilizes the Spotify API. My goal is to utilize the user input data to trigger calls to the Spotify API on the server and then relay the results back to the front end. However, I have encou ...

Ways to execute the pdf.js node demonstrations?

I've been attempting to run the pdf.js node examples, specifically getinfo.js. Unfortunately, I encountered an issue that resulted in the following error: C:\Repositories\pdf.js>node getinfo.js node:internal/modules/cjs/loader:1080 thro ...

Is there a way for me to send a trading view post request to my Node.js application?

My nodeJS application is set up to receive a post request from TV. When the TV sends a POST request with data and application/json headers, my app ends up receiving an empty req.body. I have included app.use(express.json()) Here's an example of the r ...

Encountering a 'Page Not Found' Message when accessing a Node.js Lambda Microservice Serverless Express.js with Compression

I'm currently grappling with understanding how the compression nodejs library operates and why it's causing issues in my specific scenario. The code I've developed is intended to be executed on AWS Lambda running nodejs 6.10. Below is my in ...

Detecting a network outage event in a FeathersJS client

Currently, I am immersed in a node.js project that utilizes featuresjs for the backend and feather-client js for the client side. The frontend is served by the backend. Here's a snippet of the backend code: app .use(compress()) .options('*&a ...

Locate Mongoose subdocuments containing specific values

Exploring My Models ActivityLanguage language_id: ID name: String Activity price: Int languages: [ActivityLanguage] I am trying to locate the Activities that contain an ActivityLanguage with a specific language_id. This method works perfectly for me (u ...