Express validator fails to validate data correctly - express

Hello i am using the latest version of express-validator to validate my requests body, the problem is when i am using notEmpty() or not().isEmpty() it always shows an error with prsonalized message i putted "text field is required" even when the text field is not empty
this is my validator.js file
import { body } from "express-validator";
export const checkPost = () => {
return [
body("text")
.trim()
.notEmpty()
.withMessage("text field is required")
];
};
this is my route.js :
router.post("/", checkPost(), uploadImg, createPost);
and this is my controller.js
export const createPost = async (req, res) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.json({ errors: errors.array() });
} ....
this is the response i get :
{
"errors": [
{
"value": "",
"msg": "text field is required",
"param": "text",
"location": "body"
}
]
}
Can anyone help me please ?

You will need a body parser middleware set up before handling the body fields. For instance, try setting your route like this (if you're sending the body as json):
router.post("/", express.json(), checkPost(), uploadImg, createPost);

After many hours of search i found that the express-validator middleware should be called after the usage of multer so changing my route this way solved the problem
router.post("/",uploadImg, checkPost(), createPost);

Related

How to create a route with Strapi 4?

I am trying to set a route. I followed a tutorial.
Everything is happening in a folder inside the api folder.
Route folder contains post.js file :
'use strict';
/**
* post router.
*/
const { createCoreRouter } = require('#strapi/strapi').factories;
module.exports = createCoreRouter('api::post.post', {
method: 'GET',
path: '/api/posts/:id/comments',
handler: 'posts.comments'
});
Controllers folder contains an other post.js file :
'use strict';
/**
* post controller
*/
const { createCoreController } = require('#strapi/strapi').factories;
module.exports = createCoreController('api::post.post', ({strapi}) => ({
comments: async (ctx) => {
return "Hello"
}
}));
Finally, when I tested URL : http://localhost:1337/api/posts/:id/comments; I have :
{
"data": null,
"error": {
"status": 404,
"name": "NotFoundError",
"message": "Not Found",
"details": {}
}
}
What did I do wrong ? Is something missing ?
I think the url should be like http://localhost:1337/api/posts/1/comments and not http://localhost:1337/api/posts/:id/comments. Means url should provide actual id instead of ':id'. Try it.

How to access object on Vue front end from axios proxy

I have a locally hosted mongodb database with mongoose, express, axios, and a Vue front end. Right now I'm trying to access a single object from an exported array, but I'm missing the mark and getting "undefined" as the result.
vue.config.js:
module.exports = {
devServer: {
proxy: 'http://localhost:3000',
}
}
here's the front end Vue script meant to use the objects:
import axios from 'axios';
export default {
name: 'Game',
data () {
return {
pages: [],
currentPage: {},
pageTitle: "",
pageText: "",
options: [],
}
},
created () {
this.getPages();
},
methods: {
async getPages() {
try {
let res = await axios.get('/api/pages');
this.pages = res.data;
console.log(this.pages);
this.currentPage = this.pages[0];
console.log(this.currentPage);
return true;
} catch (error) {
console.log(error);
}
},
my "get" endpoint in pages.js:
router.get('/', async (req, res) => {
try {
let pages = await Page.find();
res.send({pages: pages}); //send result of search for pages as list of pages called "pages"
} catch (error) {
console.log(error);
res.sendStatus(500); //500 = server could not fulfill request
}
});
the route in server.js:
const pages = require('./routes/pages');
app.use('/api/pages', pages);
app.listen(3000, () => console.log('Server listening on port 3000!'));
module.exports = app;
and here's the console output, with the "pages" object from vue's data property and the "currentPage" that's supposed to be at pages[0] (printed to console in earlier example):
I can access the api at 'localhost:3000/api/pages' just fine, but how do I break into that array and access the first page object? I want to get an object from the list axios fetches from mongoose, then hold that object in a variable so I can access it's properties. The whole "pages > [[Target]] > pages > [ ]" is part of the problem I'm sure, but I don't know what to tell the code to open it.
Whoops! I realized my mistake. In pages.js I should have sent "res.send(pages);" After a whole couple days too XD

Cannot read property 'context' of undefined - GraphQL

I am using Typescript, Express, TypeORM, GraphQL and TypeGraphQL to build a small app that allows the user to login.
However, when I hit my test query bye on the GraphQL playground, I get:
Cannot read property 'context' of undefined
"TypeError: Cannot read property 'context' of undefined",
" at new exports.isAuth // isAuth is a JS file I wrote
MyContext.js
import { Request, Response } from "express";
export interface MyContext {
req: Request;
res: Response;
payload?: { userId: string };
}
isAuth.js
import { MiddlewareFn } from "type-graphql";
import { verify } from "jsonwebtoken";
import { MyContext } from "./MyContext";
export const isAuth: MiddlewareFn<MyContext> = ({ context }, next) => {
const authorization = context.req.headers["authorization"];
if (!authorization) {
throw new Error("not authorized");
}
...
UserResolver
#Query(() => String)
#UseMiddleware(isAuth)
bye(#Ctx() { payload }: MyContext) {
console.log(payload);
return `your user id is: ${payload!.userId}`;
}
I am not sure why the context is undefinied in the file isAuth.js
SOLVED thanks to: https://github.com/MichalLytek/type-graphql/issues/433
1) Go into ./tsconfig.json
2) Change "target": "es5" to "target": "es6"

Database error handling with Sequelize when column doesn't exist?

I'm trying to handle different errors that might show up when inserting into a MYSQL database.
Using Sequelize with express.
My foo.js model file looks like this:
module.exports = (sequelize, type) => {
return sequelize.define('event', {
id: {
type: type.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: type.STRING,
}
},{
freezeTableName: true,
rejectOnEmpty: true,
})
}
and my route file (or whatever you wanna call it), looks like this.
const Sequelize = require('sequelize')
const fooModel = require('../../models/Foo')
const router = require('express').Router();
const auth = require('../auth');
const bodyParser = require('body-parser');
const sequelize = new Sequelize('username', 'password', 'db', {
host: 'localhost',
dialect: 'mysql'
})
const Foo = fooModel(sequelize, Sequelize);
router.use(bodyParser.json({limit: '100mb'}));
router.use(bodyParser.urlencoded({ extended: true, limit: '100mb', parameterLimit: 1000000 }));
sequelize.sync({force: true})
.then(() => {
console.log('Worked');
});
router.post('/', (req,res,next) => {
if(Object.keys(req.body).length > 0){
return Foo.create({
Name: req.body.Name
}).then((result) => {
if(result){
return res.status(200).json(result);
}else{
return res.status(400).json({'error': 'Could not create record.'});
}
}).catch(Sequelize.DatabaseError, function(err){
return res.status(400).json(err);
}).catch(function(err){
res.send(err);
})
}else{
return res.status(400).json({'error': 'error'});
}
});
module.exports = router;
Whenever I try to post to the route with something like:
{
"name": "test",
"foo": "bar"
}
Sequelize accepts the body and puts "test" in the ”name” column, and ignores the "foo" column, because the "foo" column does not exist. Meaning, all I get back once it's posted is:
{"id": "123",
createdAt: 2020-01-23 13:337:00
updatedAt: 2020-01-23 13:337:00
}
And not an error as I expect.
What Im trying to do, is catch that error (that I today ain't recieving) whenever I try to post to a column that doens't exist, basically replicate a normal MYSQL error behaviour.
Could someone point me in the right direction on what I'm missing?
In my experience, it would be better to avoid this particular problem by validating the fields on the client side.
But, you can trap such a condition in js. You'll not get a DB exception because Sequelize isn't sending your unrecognized attributes to the database.
if (!Foo.attributes.hasOwnProperty('foo')) {
// some error handing here, for invalid field.
}
You could write a utility function to iterate through the attributes of req.body and send an appropriate error to the response.
FWIW, you'll find that Name is also invalid, because your model specifies(lower case) name
hth

adding a query to an axios get request

I am trying to restrict what gets returned by my axios get request.
I have a firebase backend and in my data i have a field called case_name, I have added a few records with the name Test and thought i could run the following in a get request to restrict my results to just those where case_name is equal to test, but it still returns all records
loadCase ({ commit, context }) {
return axios.get('http', {
params: {
case_name: 'Test'
}
})
.then(res => {
const convertcase = []
for (const key in res.data) {
convertcase.push({ ...res.data[key], id: key })
}
commit('listcase', convertcase)
})
.catch(e => context.error(e));
},
Can anyone tell me what im doing wrong please as cant find anything to help me at the moment
my returned object is
data: {…}
​​
"-LFXvk9yY5c-O8yIdf8k": Object { case_name: "Test", case_status: "live", case_summary: "This is some summary content", … }
​​
"-LFXwmv6eHqZs8jndNay": Object { case_name: "case 2", case_status: "live", case_summary: "dasdasdasdasd\nasd\ndasd\na\nsdasdasd", … }
​​
"-LFc2t9V7LVqnLAlIjoU": Object { case_name: "Test", case_status: "live", case_summary: "this is just another summary", … }
Thanks