Cant read vaules from JavaScript Object always undifined - javascript

I can't retrieve values from a JavaScript object.
I have tried several ways but I can't get it to work the usual way i now but i am pretty new in javaScript.
Thanks for your time and attention, if there is anything missing or you need some more information please contact me.
The Object form consol.log(unpackedReq)
{
'mFile ': {
name: 'test',
data: { type: 'Buffer', data: [Array] },
size: 4,
encoding: '7bit',
tempFilePath: '',
truncated: false,
mimetype: 'application/octet-stream',
md5: '098f6bcd4621d373cade4e832627b4f6'
}
}
My Code:
app.post('/single', async(req, res, next) => {
try {
const unpackedReq = JSON.parse(JSON.stringify(req.files));
const file = unpackedReq.mFile
console.log(unpackedReq)
console.log(typeof(unpackedReq)) //object
console.log(unpackedReq["mFile"].name) // TypeError: Cannot read properties of undefined (reading 'name')
} catch (error) {
console.log(error)
res.send('Error uploading file')
}
The Full error:
> TypeError: Cannot read properties of undefined (reading 'name')
> at /Users/lukasbronstering/VsCode/ftp-web-server/app.js:25:42
> at Layer.handle [as handle_request] (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/layer.js:95:5)
> at next (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/route.js:144:13)
> at Route.dispatch (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/route.js:114:3)
> at Layer.handle [as handle_request] (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/layer.js:95:5)
> at /Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/index.js:284:15
> at Function.process_params (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/index.js:346:12)
> at next (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/index.js:280:10)
> at jsonParser (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/body-parser/lib/types/json.js:119:7)
> at Layer.handle [as handle_request] (/Users/lukasbronstering/VsCode/ftp-web-server/node_modules/express/lib/router/layer.js:95:5)

There is a space in object 'mFile ' and you're accessing it without space.
so you can just add the space while accessing your object like this console.log(unpackedReq["mFile "].name) or you could change your object. but i would recommend to change your object name

Related

TypeError: Cannot read property 'isPaused' of null

I'm trying to use wavesurfer.js in my vue front-end app. After I get the link to the audio file from the backend I get this error:
wavesurfer.js?8896:5179 Uncaught (in promise) TypeError: Cannot read property 'isPaused' of null
at WaveSurfer.empty (wavesurfer.js?8896:5179)
at WaveSurfer.load (wavesurfer.js?8896:4852)
at _callee$ (GameScreen.vue?dcce:42)
at tryCatch (runtime.js?96cf:63)
at Generator.invoke [as _invoke] (runtime.js?96cf:293)
at Generator.eval [as next] (runtime.js?96cf:118)
at asyncGeneratorStep (asyncToGenerator.js?1da1:3)
at _next (asyncToGenerator.js?1da1:25)
at eval (asyncToGenerator.js?1da1:32)
at new Promise (<anonymous>)
This is the code I'm using in my vue component
<script>
import axios from 'axios';
import wavesurfer from 'wavesurfer.js';
export default {
name: 'GameScreen',
data(){
return {
isLoading: true,
}
},
mounted(){
this.initAudio();
},
methods: {
initAudio(){
axios.get('http://localhost:6060/track').then( async (response) => {
console.log(response.data);
const waveform = new wavesurfer({
container: this.$refs.wave,
color: 'violet',
backend: 'MediaElement'
});
await waveform.load(response.data);
await waveform.on('ready', () => {
this.isLoading = false;
//waveform.play();
});
console.log(waveform);
});
}
}
}
</script>
Is there any error in the code or something I can do to fix this?
UPDATE
The question is closed, I wanted to post the solution but not possible. Anyway the problem was with a typo I've made when the library is instantiated. I forget to call the create method. to instantiate correctly WaveSurfer the syntax is new WaveSurfer.create({...}) and not only new WaveSurfer({})
Thank you all for the help.

Cloud function fails after changing Runtime to Node.js 10

I am trying to take firebase backup through a cloud function. The function was running completely fine when I was using Runtime: Node.js 8. However, since it is going to be deprecated soon, I now have to use Node.js 10. My fcloud function now fails with the below error:
Error: function execution failed. Details:
Cannot read property 'charCodeAt' of undefined
Detailed error log:
2020-05-27 11:01:21.820 IST
firestore_export
8kxlp9s867dy
TypeError: Cannot read property 'charCodeAt' of undefined at peg$parsetemplate (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:304:17) at Object.peg$parse [as parse] (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:633:18) at new PathTemplate (/workspace/node_modules/google-gax/build/src/pathTemplate.js:55:54) at segments.forEach.segment (/workspace/node_modules/google-gax/build/src/pathTemplate.js:120:29) at Array.forEach (<anonymous>) at PathTemplate.render (/workspace/node_modules/google-gax/build/src/pathTemplate.js:114:23) at FirestoreAdminClient.databasePath (/workspace/node_modules/#google-cloud/firestore/build/src/v1/firestore_admin_client.js:904:57) at exports.scheduledFirestoreBackup (/workspace/index.js:6:31) at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/invoker.js:330:28) at process._tickCallback (internal/process/next_tick.js:68:7)
Expand all | Collapse all
{
insertId: "000000-f688386c-8f2b-4146-aaf7-1fe67c656fa2"
labels: {…}
logName: "projects/firestore-249705/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
receiveTimestamp: "2020-05-27T05:31:31.171084310Z"
resource: {…}
severity: "ERROR"
textPayload: "TypeError: Cannot read property 'charCodeAt' of undefined
at peg$parsetemplate (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:304:17)
at Object.peg$parse [as parse] (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:633:18)
at new PathTemplate (/workspace/node_modules/google-gax/build/src/pathTemplate.js:55:54)
at segments.forEach.segment (/workspace/node_modules/google-gax/build/src/pathTemplate.js:120:29)
at Array.forEach (<anonymous>)
at PathTemplate.render (/workspace/node_modules/google-gax/build/src/pathTemplate.js:114:23)
at FirestoreAdminClient.databasePath (/workspace/node_modules/#google-cloud/firestore/build/src/v1/firestore_admin_client.js:904:57)
at exports.scheduledFirestoreBackup (/workspace/index.js:6:31)
at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/invoker.js:330:28)
at process._tickCallback (internal/process/next_tick.js:68:7)"
timestamp: "2020-05-27T05:31:21.820Z"
trace: "projects/firestore-249705/traces/74e27700d135763bc4e7892ebb1a2333"
}
My index.js is as below:
const firestore = require('#google-cloud/firestore');
const client = new firestore.v1.FirestoreAdminClient();
// Replace BUCKET_NAME
const bucket = 'gs://gcp_firestore_ae2/firestore_export'
exports.scheduledFirestoreBackup = (event, context) => {
const databaseName = client.databasePath(
process.env.GCLOUD_PROJECT,
'(default)'
);
return client
.exportDocuments({
name: databaseName,
outputUriPrefix: bucket,
// Leave collectionIds empty to export all collections
// or define a list of collection IDs:
// collectionIds: ['users', 'posts']
collectionIds: ['most_valuable_items','nric_img','pay_slip','pic_of_ofc_entrance'],
})
.then(responses => {
const response = responses[0];
console.log(`Operation Name: ${response['name']}`);
return response;
})
.catch(err => {
console.error(err);
});
};
I had the same issue. I fixed it by changing:
process.env.GCLOUD_PROJECT
to my actual Project ID (e.g. "my_app_37274")
I had the same issue, It seems like in previous versions we don't need to GCLOUD_PROJECT in environment variable i.e it automatically detects it, but from node 10 onwards we need to pass this explicitly.
That's how I resolved it.
So instead of hardcoding it, try passing GCLOUD_PROJECT in cloud functions environment variables.
Note: GCLOUD_PROJECT is project id, not the project name.

Updating a post in Meteor.js

I just recently started to try learning Meteor.js. My intention is to build a newsfeed-feature where I can insert, edit and delete content. I’m stuck at the edit part.
imports/api/news/methods.js
Meteor.methods({
'news.insert'(content, title) {
check(content, String);
check(title, String);
// Make sure the user is logged in before insertig content
if (! Meteor.userId()) {throw new Meteor.Error('not-authorized');}
return News.insert({
content,
title,
createdAt: new Date(),
});
},
'news.remove'(newsId) {
check(newsId, String);
News.remove(newsId);
},
// Doesn't work?
'news.update'(content, title, newsId) {
check(content, String);
check(title, String);
check(newsId, String);
// user has to be logged in before updating content
if (! Meteor.userId()) {throw new Meteor.Error('not-authorized');}
News.update({_id: newsId}), {
$set: {
title:title,
content:content
}
}
}
});
I inserted a route that leads to the update-form for the content:
Edit
The update-form: imports/ui/components/news_edit/news_edit.html
<template name="NewsEdit">
<div class="col">
<small>Update: <b>{{news.content}}</b></small>
<form class='news-link-update'>
<input type="text" name="content" value="{{news.content}}" required> <small>ID: {{news._id}}</small> <br>
<br>
<textarea class="form-control" rows="5" id="comment" name="title" required>{{news.title}}</textarea>
<br>
<input type="submit" name="update" value="Update News" class="submit">
</form>
</div>
</template>
And the js-file which is calling the method: imports/ui/components/news_edit/news_edit.js
import { News } from '/imports/api/news/news.js';
import { Meteor } from 'meteor/meteor';
import './news_edit.html';
Template.NewsEdit.helpers({
news: ()=> {
var id = FlowRouter.getParam('id');
return News.findOne({_id: id});
}
});
Template.NewsEdit.events({
'submit .news-link-update'(event) {
event.preventDefault();
const target = event.target;
let newsId = target.dataset.newsId;
const title = target.elements.title;
const content = target.elements.content;
Meteor.call('news.update', title.value, content.value, newsId, (error, result) => {
if (error) {
console.log(newsId);
alert(error.reason);
}
});
},
});
I don't get a error 400 anymore but a 500-error. Internal server error.
The id is referenced now.
I20190222-04:22:58.230(1)? Exception while invoking method 'news.update' Error: Invalid modifier. Modifier must be an object.
I20190222-04:22:58.233(1)? at MongoConnection._update (packages/mongo/mongo_driver.js:495:11)
I20190222-04:22:58.233(1)? at MongoConnection.<anonymous> (packages\meteor.js:376:21)
I20190222-04:22:58.234(1)? at MongoConnection.(anonymous function) [as update] (packages/mongo/mongo_driver.js:754:49)
I20190222-04:22:58.234(1)? at _0xb3b0x8.(anonymous function).update (packages/mongo/collection.js:585:31)
I20190222-04:22:58.235(1)? at _0xb3b0x8.(anonymous function).Mongo.Collection.(anonymous function) [as update] (packages/aldeed:collection2/collection2.js:213:19)
I20190222-04:22:58.236(1)? at MethodInvocation.news.update (imports/api/news/methods.js:40:10)
I20190222-04:22:58.236(1)? at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1767:12)
I20190222-04:22:58.237(1)? at DDP._CurrentMethodInvocation.withValue (packages/ddp-server/livedata_server.js:719:19)
I20190222-04:22:58.237(1)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1304:12)
I20190222-04:22:58.238(1)? at DDPServer._CurrentWriteFence.withValue (packages/ddp-server/livedata_server.js:717:46)
I20190222-04:22:58.239(1)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1304:12)
I20190222-04:22:58.239(1)? at Promise (packages/ddp-server/livedata_server.js:715:46)
I20190222-04:22:58.242(1)? at new Promise (<anonymous>)
I20190222-04:22:58.242(1)? at Session.method (packages/ddp-server/livedata_server.js:689:23)
I20190222-04:22:58.243(1)? at packages/ddp-server/livedata_server.js:559:43
I20190222-04:23:28.905(1)? Exception while invoking method 'news.update' Error: Invalid modifier. Modifier must be an object.
I20190222-04:23:28.906(1)? at MongoConnection._update (packages/mongo/mongo_driver.js:495:11)
I20190222-04:23:28.910(1)? at MongoConnection.<anonymous> (packages\meteor.js:376:21)
I20190222-04:23:28.911(1)? at MongoConnection.(anonymous function) [as update] (packages/mongo/mongo_driver.js:754:49)
I20190222-04:23:28.911(1)? at _0xb3b0x8.(anonymous function).update (packages/mongo/collection.js:585:31)
I20190222-04:23:28.912(1)? at _0xb3b0x8.(anonymous function).Mongo.Collection.(anonymous function) [as update] (packages/aldeed:collection2/collection2.js:213:19)
I20190222-04:23:28.912(1)? at MethodInvocation.news.update (imports/api/news/methods.js:40:10)
I20190222-04:23:28.913(1)? at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1767:12)
I20190222-04:23:28.914(1)? at DDP._CurrentMethodInvocation.withValue (packages/ddp-server/livedata_server.js:719:19)
I20190222-04:23:28.915(1)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1304:12)
I20190222-04:23:28.916(1)? at DDPServer._CurrentWriteFence.withValue (packages/ddp-server/livedata_server.js:717:46)
I20190222-04:23:28.918(1)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1304:12)
I20190222-04:23:28.918(1)? at Promise (packages/ddp-server/livedata_server.js:715:46)
I20190222-04:23:28.919(1)? at new Promise (<anonymous>)
I20190222-04:23:28.920(1)? at Session.method (packages/ddp-server/livedata_server.js:689:23)
I20190222-04:23:28.920(1)? at packages/ddp-server/livedata_server.js:559:43
I20190222-04:25:34.580(1)? Exception while invoking method 'news.update' Error: Invalid modifier. Modifier must be an object.
I20190222-04:25:34.583(1)? at MongoConnection._update (packages/mongo/mongo_driver.js:495:11)
I20190222-04:25:34.584(1)? at MongoConnection.<anonymous> (packages\meteor.js:376:21)
I20190222-04:25:34.585(1)? at MongoConnection.(anonymous function) [as update] (packages/mongo/mongo_driver.js:754:49)
I20190222-04:25:34.585(1)? at _0xb3b0x8.(anonymous function).update (packages/mongo/collection.js:585:31)
I20190222-04:25:34.586(1)? at _0xb3b0x8.(anonymous function).Mongo.Collection.(anonymous function) [as update] (packages/aldeed:collection2/collection2.js:213:19)
I20190222-04:25:34.587(1)? at MethodInvocation.news.update (imports/api/news/methods.js:40:10)
I20190222-04:25:34.587(1)? at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1767:12)
I20190222-04:25:34.588(1)? at DDP._CurrentMethodInvocation.withValue (packages/ddp-server/livedata_server.js:719:19)
I20190222-04:25:34.593(1)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1304:12)
I20190222-04:25:34.594(1)? at DDPServer._CurrentWriteFence.withValue (packages/ddp-server/livedata_server.js:717:46)
I20190222-04:25:34.594(1)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1304:12)
I20190222-04:25:34.594(1)? at Promise (packages/ddp-server/livedata_server.js:715:46)
I20190222-04:25:34.595(1)? at new Promise (<anonymous>)
I20190222-04:25:34.596(1)? at Session.method (packages/ddp-server/livedata_server.js:689:23)
I20190222-04:25:34.597(1)? at packages/ddp-server/livedata_server.js:559:43
I20190222-04:27:21.274(1)? Exception while invoking method 'news.update' Error: Invalid modifier. Modifier must be an object.
I20190222-04:27:21.277(1)? at MongoConnection._update (packages/mongo/mongo_driver.js:495:11)
I20190222-04:27:21.278(1)? at MongoConnection.<anonymous> (packages\meteor.js:376:21)
I20190222-04:27:21.279(1)? at MongoConnection.(anonymous function) [as update] (packages/mongo/mongo_driver.js:754:49)
I20190222-04:27:21.280(1)? at _0xb3b0x8.(anonymous function).update (packages/mongo/collection.js:585:31)
I20190222-04:27:21.280(1)? at _0xb3b0x8.(anonymous function).Mongo.Collection.(anonymous function) [as update] (packages/aldeed:collection2/collection2.js:213:19)
I20190222-04:27:21.281(1)? at MethodInvocation.news.update (imports/api/news/methods.js:40:10)
I20190222-04:27:21.282(1)? at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1767:12)
I20190222-04:27:21.283(1)? at DDP._CurrentMethodInvocation.withValue (packages/ddp-server/livedata_server.js:719:19)
I20190222-04:27:21.283(1)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1304:12)
I20190222-04:27:21.286(1)? at DDPServer._CurrentWriteFence.withValue (packages/ddp-server/livedata_server.js:717:46)
I20190222-04:27:21.286(1)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1304:12)
I20190222-04:27:21.287(1)? at Promise (packages/ddp-server/livedata_server.js:715:46)
I20190222-04:27:21.288(1)? at new Promise (<anonymous>)
I20190222-04:27:21.289(1)? at Session.method (packages/ddp-server/livedata_server.js:689:23)
I20190222-04:27:21.289(1)? at packages/ddp-server/livedata_server.js:559:43
^ This is the new error log. What does the invalid modifier part mean?
You are getting Error: Invalid modifier. Modifier must be an object. error because of a syntax error in the update statement of the server method.
imports/api/news/methods.js
Meteor.methods({
...
news.update(content, title, newsId) {
check(content, String);
check(title, String);
check(newsId, String);
// user has to be logged in before updating content
if (! Meteor.userId()) {throw new Meteor.Error('not-authorized');}
// *** The parentheses was closed before '$set' was passed ***
News.update({_id: newsId}, {
$set: {
title:title,
content:content
},
{
multi:false // optional since by default it is false
}
});
}
});

Error "TypeError: Cannot read property 'indexOf' of undefined" when using ipfs-api

I was performing development using ipfs - api, I encountered the following error, add of image file to ipfs node does not work well.
Looking at the details of the error, it seems that protocol is treated as undefined among if (protocol.indexOf ('https') === 0) { in request.js.
This is the error description
Uncaught (in promise) TypeError: Cannot read property 'indexOf' of undefined
at webpackJsonp../node_modules/ipfs-api/src/utils/request.js.module.exports (request.js:7)
at requestAPI (send-request.js:165)
at send (send-request.js:196)
at send-files-stream.js:99
at Function.promisify (add.js:41)
at index.js:32
at Object.add (add.js:60)
at VueComponent._callee$ (HaikuCompose.vue?0664:118)
at tryCatch (runtime.js:62)
at Generator.invoke [as _invoke] (runtime.js:296)
This is the code I wrote
import IPFS from "ipfs-api"
const ipfsConf = { host: process.env.IPFSHOST, port: process.env.IPFSPORT, protocol: process.env.IPFSPROTCOL }
const ipfs = new IPFS(ipfsConf)
export default {
name: 'ipfstest',
data() {
return {
file:null,
buffer:null,
ipfsHash:null,
}
},
methods: {
async addipfs() {
await ipfs.add(this.buffer, (err, ipfsHash) => {
console.log(err,ipfsHash);
this.ipfsHash = ipfsHash[0].hash;
})
},
From the module sources, indexOf on line 7 of the request.js file is used on the variable storing the protocol, which is undefined in your case.
And from your code, I think I can safely assume that your environment variable process.env.IPFSPROTCOL is undefined.
TL:DR : I think you wanted to write IPFSPROTOCOL instead of IPFSPROTCOL

TypeError: req.checkBody(...).optional(...).isDate is not a function

I am facing issues using the express validator specifically it is the isDate function. I have taken steps to use expressvalidator, the bodyparse, validator module etc. All routes are after this only..
Environment is Node + Express.
The issue is on the usage of
"req.checkBody('date_of_birth', 'Invalid date').optional({ checkFalsy: true }).isDate();"
and I keep getting the following error.
TypeError: req.checkBody(...).optional(...).isDate is not a function
at exports.author_create_post (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/controllers/authorController.js:47:81)
at Layer.handle [as handle_request] (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/layer.js:95:5)
at /Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:335:12)
at next (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:174:3)
at router (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:317:13)
at /Users/svitaworld/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:335:12)
at next (/Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:275:10)
at /Users/mycomputer/Desktop/NodeJS/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:635:15
app.js
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(expressValidator()); // Add this after the bodyParser middlewares!
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/catalog', catalog); // Add catalog routes to middleware chain.
in one of my controllers, I am using the isDate() method to do some validation on date that I have separately defined int he AuthorSchema.
var AuthorSchema = Schema( {
first_name: {type: String, required: true, max: 100},
family_name: {type: String, required: true, max: 100},
date_of_birth: {type: Date},
date_of_death: {type: Date},
} );
Now to handle the post requests I have this code in the controller:
authorController.js -- line from line 41-48
// Handle Author create on POST
exports.author_create_post = function(req, res, next) {
console.log("DEBUG: starting in exports.author_create_post");
req.checkBody('first_name', 'First name must be specified.').notEmpty();
req.checkBody('family_name', 'Family name must be specified.').notEmpty();
req.checkBody('family_name', 'Family name must be alphanumeric text.').isAlpha();
req.checkBody('date_of_birth', 'Invalid date').optional({ checkFalsy: true }).isDate(); // Error is on this usage of isDate()
req.checkBody('date_of_death', 'Invalid date').optional({ checkFalsy: true }).isDate();
isDate() has been removed from validator.js. You can see this commit on GitHub for more information. express-validator uses validator.js for validation.
You can make a custom validator to check for valid dates. For the new API:
check('date').custom(isValidDate).withMessage('the date must be valid');
For the legacy API:
app.use(expressValidator({
customValidators: {
isValidDate: isValidDate
}
}));
when you apply the middleware (in app.js or something similar) and for checking:
req.checkBody('date', 'the date must be valid').isValidDate();
isValidDate() has to be written by yourself. Here is an example:
function isValidDate(value) {
if (!value.match(/^\d{4}-\d{2}-\d{2}$/)) return false;
const date = new Date(value);
if (!date.getTime()) return false;
return date.toISOString().slice(0, 10) === value;
}
This checks for dates with the yyyy-mm-dd format. It was taken from this answer. There are also plenty of other answers for different formats here on Stack Overflow:
mm/dd/yyyy
dd/mm/yyyy
Or use moment's isValid().

Categories