How to validate Axios request with Express Validator?
I'm trying to figure out how to use Express Validator to validate my Axios POST
request. Express Validator works perfectly when validating fields attached directly to req.body
, but when using Axios, I can only seem to access the body via req.body.data
and this is causing problems with the validation.
Middleware in validator.js
const { validationResult } = require("express-validator");
function validator(req, res, next) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
} else {
next();
}
}
module.exports = validator;
Routes userRoutes.js
const express = require("express");
const router = express.Router();
const validator = require("../../middleware/validator");
const { body } = require("express-validator");
const { registerUser } = require("../../controllers/userController");
router.post("/register", [body("email").isEmail(), validator], registerUser);
module.exports = router;
I've tired passing req.body.data
directly into validationResult
but just caused an error. I also tried using the check
middleware from express-validator
but this didn't work either.
Is there a way to validate nested fields in the body?, or perhaps a way to get Axios to attach the POST
data directly to req.body
not req.body.data
?
Axios request
import axios from 'axios';
axios({
method: "post",
baseURL: "http://localhost:3001",
url: "/api/users/register",
data: {
"email": "text-text@gmail.com"
}
})
Thanks in advance! Kyle.
See also questions close to this topic
-
vue hot reload works but refresh page doesn't
I'm using vue2. I have a page listing members of my website. When I modify the code, the hot reloading works fine and my table displays fine. But when I refresh the page, the table is still fine (checked in VueJS devtools) but it doesn't display because the array I'm iterating becomes undefined. what should I do? weird bug isn't it? by the way I'm using props to pass the data to a 'listing' component.
props: ['table'], name: 'ListTable', components : { // UserCard }, data() { return { items: [], currentSort: 'id', currentSortDir: 'asc', pageSize: 10, currentPage: 1 } }, mounted() { this.items = this.$props.table.rows; // becomes undefined after page refresh, hot reloading works fine though },
-
How to prevent toggling class to go on top of page in vanilla JS?
I'm working on a website where users can click on a link in the header and it toggles a class to make an element appear. This is working, but every time I try it the page goes back to the top. How can I prevent this?
This is my code:
function openModal(e) { e.parentNode.classList.toggle("modal-open") }
header { position: fixed; top: 0; left: 0; width: 100%; } .modal { width: 100%; height: 100vh; background-color: red; position: fixed; top: 0; left: 100%; z-index: 999; } .modal-open .modal { left: 0; }
<header> <p class="open" onclick="openModal(this)">Open</p> <div class="modal" onclick="openModal(this)"> Content modal </div> </header>
Thanks for your answers!
-
Variable value not being saved in function
I want my filters variable to update, my guess is it's re-initializing as the set value every time the function is called, whenever i try to declare it outside of the function I get a lexical error, how can I make sure it keeps the value assigned to it after a button has clicked
export function categoryRender(){ let filter = 'RICK' console.log(filter) const all = document.getElementById('all'); all.onclick = function(){ filter = 'ALL' render(filter); } categories = categories.sort(); const filterContainer = document.getElementById("filter-container"); filterContainer.innerHTML = ""; const allFilterImg = document.getElementById('all-image'); if (filter === 'ALL'){ allFilterImg.setAttribute('src', './images/checked.jpeg') }else{ allFilterImg.setAttribute('src', './images/unchecked.png') console.log('unchecked all firing') } for (let i = 0; i < categories.length; i++){ const line = document.createElement("span"); const filterButton = document.createElement("img"); const filterLabel = document.createElement("h2"); filterContainer.appendChild(line); line.appendChild(filterButton); line.appendChild(filterLabel); line.setAttribute('id', categories[i]); line.classList.add('filter-line'); filterLabel.innerHTML = categories[i]; if (filter === categories[i]){ filterButton.setAttribute('src', './images/checked.jpeg') }else{ filterButton.setAttribute('src', './images/unchecked.png') } line.onclick = function(){ filter = categories[i]; render(filter) } } }
-
how to create poll using API with react functional component
this is my react js code and I want to connect with my node js API but I don't understand how to that ...!
import React, { useState } from "react"; import Poll from "react-polls"; // import "./styles.css"; /** * https://stackoverflow.com/questions/65896319/react-js-class-poll-convert-into-react-hooks-poll */ // Declaring poll question and answers const pollQuestion = "Youtube is the best place to learn ?"; const answers = [ { option: "Yes", votes: 7 }, { option: "No", votes: 2 }, { option: "don't know", votes: 1 }, ]; const Fakepolls = () => { // Setting answers to state to reload the component with each vote const [pollAnswers, setPollAnswers] = useState([...answers]); // Handling user vote // Increments the votes count of answer when the user votes const handleVote = (voteAnswer) => { setPollAnswers((pollAnswers) => pollAnswers.map((answer) => answer.option === voteAnswer ? { ...answer, votes: answer.votes + 1, } : answer ) ); }; return ( <div> <Poll noStorage question={pollQuestion} answers={pollAnswers} onVote={handleVote} /> </div> ); }; export default function App() { return ( <div className="App"> <Fakepolls /> </div> ); }
It work's fine with
// Declaring poll question and answers const pollQuestion = "Youtube is the best place to learn ?"; const answers = [ { option: "Yes", votes: 7 }, { option: "No", votes: 2 }, { option: "don't know", votes: 1 }, ];
but I want to connect this poll with my API instead of Declaring it ..! this is my api- to get data -> ( router.get("/poll/:pollId", getPoll); //)
exports.getPoll = async (req, res, next) => { try { const { pollId } = req.params; const polls = await Poll.findById(pollId); if (!polls) throw new Error("no polls found"); res.status(200).json(polls); } catch (error) { error.status = 400; next(error); } };
and this API for POST data- and my node js code -
exports.votes = async (req, res, next) => { try { /** * 1. get the poll from db * 2. check if the user already exists in any option * 3. if user has already selected any option do nothing * 4. if user has selected any other option remove from that option * 5. if user does not exist in any option, insert his user id to selected option */ const { pollId } = req.params; let { userId, answer } = req.body; // get selected poll from db const poll = await Poll.findById(pollId); if (answer && poll) { answer = answer.toLowerCase(); ///Finf the Poll let existingVote = null; Object.keys(poll.options).forEach((option) => { // loop on all options, check if the user already exists in any option if (poll.options[option].includes(userId)) { existingVote = option; } }); if (existingVote == null) { // if there is no existing vote save it to db try { const push = {}; push[`options.${answer}`] = userId; const update = await Poll.findByIdAndUpdate( pollId, { $push: push }, { upsert: true } ); res.status(201).json(update); } catch (err) { error.status = 400; next(error); } } else if (existingVote && existingVote.length > 0) { // check if answer is same as previous, if yes send not modified if (existingVote.toLowerCase() === answer.toLowerCase()) { res.status(304).send("Response already saved"); } else { // delete the previous response and save it in new if ( Array.isArray(poll.options[existingVote]) && poll.options[existingVote].length > 0 ) { // TODO: filtering this is not returning array but 1 poll.options[existingVote] = poll.options[existingVote].filter( (vote) => vote != userId ); poll.options[answer] = poll.options[answer].push(userId); const update = await Poll.findByIdAndUpdate(pollId, { $set: { options: poll.options }, }); res.status(201).json(update); } } } else { error = { status: 500, message: "Something went wrong", }; next(error); } } else { error = { status: 404, message: "Poll not found", }; next(error); } } catch (error) { error.status = 400; next(error); } };
this is a POSTMAN image using POST to store data --- >
how can I connect API with react poll
-
Set HttpOnly Cookies while developing Web App locally
I am developing a web app with angular + nebular auth. Nebular auth is working and I get a JWT token from our auth server. The auth server is made with Node and sets also an HTTPOnly cookie for the refresh token. I want this token to be send along every request. The login response has indeed the Set-Cookie header, but the cookie is never set. I have read a lot of answers in Stack Overflow but everything I tried did not work.
The auth server is in a Cloud server, while I am developing the app locally. This maybe can be a problem already.
Anyway, here's what I have done till now:
Node.js
I am using an HTTP server, and setting the cookie with cookie-parser with:
res.cookie("refresh_token", token, {httpOnly: true, maxAge: ....});
I set the core options in app.js like this:
app.use(cors({ credentials: true, origin: ["http://localhost:4200", "http://127.0.0.1:4200"] exposedHeaders = ["Content-Length", .....], allowedHeaders = ["Content-Type", "Authorization", "Set-Cookie", ....], }));
When I get the response of the Login, I do get the Set-Cookie header but I cannot see the cookie in the Cookies tab of my browser console.
I tried to send a request from Angular anyway, with
{ headers: headers, withCredentials: true }
but obviously when I check the cookie in Node there's nothing.So I am going crazy... it's probably a problem with CORS, because I am developing from localhost and the server is up on the cloud?
How can I make this work?
-
newMember.guild.channels.cache.find not working in my discord bot's code
I am trying to make a Discord bot for a friend. The purpose of the bot would be to add a role to any member of a specific voice channel and remove it when they leave the channel. Here is the code:
client.on('voiceStateUpdate', (oldMember, newMember) => { // définition des constantes const testChannel = newMember.guild.channels.cache.find(c => c.name === '🕐 1h de travail'); const role = newMember.guild.roles.cache.find(r => r.name === 'test'); // détection if (newMember.channelID === testChannel.id) { // Triggered when the user joined the channel we tested for if (!newMember.member.roles.cache.has(role)) newMember.member.roles.add(role); // Add the role to the user if they don't already have it } else if (oldMember.member.roles.cache.has(role)) oldMember.member.roles.remove(role); } });
When I launch the bot using
npm run dev
and then join a voice channel, I get this error:/home/archie/Documents/my-bot/index.js:13 const testChannel = newMember.guild.channels.cache.find(c => c.name === '🕐 1h de travail'); ^ TypeError: Cannot read property 'find' of undefined at Client.<anonymous> (/home/archie/Documents/my-bot/index.js:13:56) at Client.emit (node:events:379:20) at VoiceStateUpdateHandler.handle (/home/archie/Documents/my-bot/node_modules/discord.js/src/client/websocket/packets/handlers/VoiceStateUpdate.js:40:16) at WebSocketPacketManager.handle (/home/archie/Documents/my-bot/node_modules/discord.js/src/client/websocket/packets/WebSocketPacketManager.js:108:65) at WebSocketConnection.onPacket (/home/archie/Documents/my-bot/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:336:35) at WebSocketConnection.onMessage (/home/archie/Documents/my-bot/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:299:17) at WebSocket.onMessage (/home/archie/Documents/my-bot/node_modules/ws/lib/event-target.js:120:16) at WebSocket.emit (node:events:379:20) at Receiver.receiverOnMessage (/home/archie/Documents/my-bot/node_modules/ws/lib/websocket.js:789:20) at Receiver.emit (node:events:379:20) [nodemon] app crashed - waiting for file changes before starting...
I don't understand it and would really appreciate your help.
-
res.download error Request Aborted on large zip file express, fast-csv, zip
I am using fast-csv to convert the data from mongodb to CSV format, and then save it to the products folder where all the banner images are also present. So I am zipping products folder with all the banner images and CSV file and return zip file with
res.download
as response on the API call.The following code only contains the necessary part.
import * as csv from "fast-csv"; const ws = fs.createWriteStream("products/file.csv"); csv .write(data, { headers: [ "_id", "name", "description", "banner", ], }) .on("finish", function () { // console.log("Write to csv successfully!"); }) .pipe(ws) .on("close", async function () { try { if (!fs.existsSync("tmp")) { fs.mkdirSync("tmp"); } await zipDir("products", "tmp/zipfile.zip"); res.download("tmp/zipfile.zip", "products.zip", async function (err) { if (err) { console.error(err); } }); } catch (error) { console.error(error); } });
This code works when there are less products and zip file is small but fails for large zip file with error
Error: Request aborted at onaborted (/home/user/project/node_modules/express/lib/response.js:1025:15) at Immediate._onImmediate (/home/user/project/node_modules/express/lib/response.js:1067:9) at processImmediate (internal/timers.js:461:21) { code: 'ECONNABORTED'
-
Multer react + node js unable to get req.file
Hi I am trying to upload a file from fronend to backend using multer
Front End
var formData = new FormData(); formData.append("files", image[0]); formData.append("data", JSON.stringify({status: 'ACK', message: "You are fu*ked"}); return http.axios .post(apiUrl + apiDomain + "/createAnnouncement", formData, { headers: { "Content-Type": "multipart/form-data", }, }) .then((res) => res);
Backend
const bodyParser = require("body-parser"); const Express = require("express"); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, config.get("announcemnt_upload_file_storage")); }, filename: function (req, file, cb) { cb(null, file.filename + "_" + Date.now()); }, }); var upload = multer({ storage: storage }); const Router = Express.Router(); Router.route("/createAnnouncement").post( upload.single("files"), (req , resp, next) => { console.log(" >>>>>>>", req.file);//THis returns undefined console.log(">>>>", req.files);//This returns undefined resp.send("Siccess") } );
Its not getting uploaded to storage and its returning undefined when called
req.file
But if I try to see
req.body
I could see[Object File] in console
PLease suggest where I am going wrong
-
ECONNRESET Aborted error randomly during node process
My node js application ( a discord bot ) keeps crashing with the
Error: aborted
message and codeECONNRESET
. I have some some digging and it seems that the issue occurs when the other end of a TCP connection hangs up abruptly.The error message I always get:
Error: aborted at connResetException (node:internal/errors:631:14) at TLSSocket.socketCloseListener (node:_http_client:438:27) at TLSSocket.emit (node:events:388:22) at node:net:666:12 at TCP.done (node:_tls_wrap:573:7) { code: 'ECONNRESET' }
As you can see the error message is not very useful and doesn't provide any informatino as to where the error happened. I am getting the error through the node
process.on('uncaughtException', err => {})
exception handler.I am using discord.js
^12.5.1
node15.4.0
and axios^0.21.1
although the error seems to occur randomly and looking through the logs there is never a specific function call that triggers it and sometimes it happens whilst no functions have even been called.The error happens sporadically as well. Sometimes it happens once a day and other times it will happen 5 times in an hour.
I should also add I am using the Heroku free tier for hosting,
If anyone could shed some light that would be very useful.
-
Cant return component after request to server - MERN
im validating the route
/users
using router, with render:<Router> <Switch> <Route path = "/" exact component = {Home}></Route> <Route path = "/login" component = {Login}></Route> <Route path = "/users" render = {verify_session}></Route> <Route component = {Not_found}></Route> </Switch> </Router>
so each time accesing to
/users
it will run the function verify_session, this one:function verify_session() { axios.get("api/cook/login/verify_session").then((response) => { if (response.data === 404) { return <Redirect to = "/login"></Redirect> }else { return <Users></Users> } }); }
this is in the backend:
router.get("/verify_session", (request, response) => { if (request.session.user != undefined) { response.json(200); }else { response.json(404); } })
it works because when i enter to
/users
without loggin i can see 404, but it isnt returning the component, if its using a simple validation:function verify_session() { let i = 1; if (i >= 1) { return <Redirect to = "/login"></Redirect> }else { return <Users></Users> } }
this way works, but with request get doesnt return anything
-
axios shows CORS error, with django rest framework
Thanks for reading. I am working with vuejs SPA with flask and django backends. Yes there are 2 backends. The application is in transition. I am switching the back end from Flask to Django Rest Framework. Some parts are still with Flask.
Problem axios POST request does not hit django server. The error in console shows as a CORS error. Same calls worked with
flask-restful
andflask-CORS
.GET request works fine with Django
Relevant code
BACKEND
settings.py
... INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders' ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL=True ...
views.py
... class SnippetView(ListCreateView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer
urls.py
... path('snippets/', SnippetListView.as_view(), name='snippet-list') ...
FRONTEND Vuejs
component
<template> <v-form ref="form" v-model="valid" > <v-text-field v-model="code" label="Code" ></v-text-field> <v-text-field v-model="text" label="text" ></v-text-field> </v-form> </template>
axios
... let snippet = { code: 'abc', text: ''} // comes from vuetifyjs form axios.post('http://localhost:8000/data/snippets', snippet) .then(res => console.log(res.data) // not working ...
Adding json data works normally in
django-admin dashboard
,django_rest_framework API interface
and inhttpie
command line clientSo it appears the issue is with axios.
I have tried
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin' : '*', 'Content-Type': 'application/x-www-form-urlencoded' }
Above have been tried separately
I have also tried with fetch, which registers the post request with server but does not return a response
I still gets cors error. The request does not even reach the server.
I have also tried different CORS settings, whitelists as mentioned here https://github.com/adamchainz/django-cors-headers
-
Is not validate data-schema
Have a code written on js (express.js). My main reason is to validate data by schema (For example, I have a schema like this: { firstName: '', lastName: '', password: ''}.
I should receive a validation error in the next cases:
- Received data is not like the defended schema above. Error schema
{ errors: {'firstName' : 'First name is required'} }
- If the route receives an extra field (for example, EMAIL (it can be any other fields and its names are unknown), should be an error too.
{ errors: {'email' : 'Extra field', '<unknown field>' : '<unknown field> is extra field'} }
- If the route receives an id field in the request body, should be an error too.
{ errors: {'id' : 'Id should be in the params'} }
I have spent 4 hours fixing this problem. Help, please.
Stack: Node.js, Express.js, express-validator. Thanks!
- Received data is not like the defended schema above. Error schema
-
Express-validator does not return any errors when validating
I am trying to validate user input when they register and test if there are errors produced in
express-validator
before saving it into the database. I am expecting that there are errors produced when I submit an empty form or whenever I fill in something that doesn't match the expected input (say email must be a valid email). However, after multiple attempts, and checking different questions that have been posted previously, I still do not understand why the middleware isn't working.Code for
routes/index.js
app.post('/signup', authenticated, userController.validateNewUser, (req, res) => { // Validate temp const errors = validationResult(req); console.log(req.body); console.log(errors); console.log(errors.array()); if (!errors.isEmpty()) { return res.send( {errors: errors.array(), message: "Error"} ); } else { // this gets executed since there are no errors apparently return res.send( {message: "OK"} ); } });
Note: I do have a
const{validationResult} = require('express-validator');
above the file.Code for
userController.validateNewUser
incontrollers/userController.js
validateNewUser: [ body('firstName') .exists() .not().isEmpty().withMessage('Cannot be empty') .isLength({ min:2, max:20 }).withMessage('First Name must be between 2 to 20 letters.') .isAlpha().withMessage('First Name must contain letters.'), body('lastName') .exists() .not().isEmpty() .isLength({ min:2, max:20 }).withMessage('Last Name must be between 2 to 20 letters') .isAlpha().withMessage('Last Name must contain letters.'), body('email') .exists() .not().isEmpty() .isEmail().withMessage('Email must be a valid email.'), ]
Note: I do have a
const{body} = require('express-validator');
above the file.OUTPUT When executing the code, filling the form with empty fields, it produces no error:
{ firstName: '', lastName: '', email: '', password: '', confirmPassword: '' } Result { formatter: [Function: formatter], errors: [] } []
Even when I fill in something (
req.body
is not empty), it doesn't produce any errors:{ firstName: 'fllllllllllllllllllllllll', lastName: 'k', email: '', password: 'dd', confirmPassword: 'ddd' } Result { formatter: [Function: formatter], errors: [] } []
Unlike previous questions, which were either due to not including a
validationResult(req)
to fetch the errors or thecheck
middleware not being used appropriately, the code does actually go through the entire validation process but captures no error. It runs fine and produces no error at all actually. I currently have no idea what might be causing this and how to fix it. It was working previously, but after changing a bit of the code, it stopped working for some reason. -
nodejs express validator seperate file problem
I want to make a Register file and add it to my router.post('/register ..');
But I got one Problem.
He shows me a unexpceted " , " . Can anyone help me?
register.js
'use strict'; const { body, validationResult } = require('express-validator'); const register = body('email').trim().isEmail().isLength({ min: 5, max: 100 }), body('url').trim().isLength({ min: 5, max: 100}), async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { const data = errors.mapped(); res.status(200).json({ data }); } } module.exports = register;
I want to make the file that I can write this:
const register = require('./register.js'); router.post('/register', register);