简体   繁体   中英

Express with FIREBASE I get TypeError: Cannot read property 'trim' of undefined

I'm working in a firebase project, and I'm trying to follow a tutorial and I can find the fix. I have seen this type of validation in other projects and it should work, but I don't know what I'm missing in my code.

I getting

TypeError: Cannot read property 'trim' of undefined

This is for a POST request

exports.createContact= (req, res)=>{
    if (req.body.body.trim() === '') {   // ERROR HERE WHEN VALIDATING

    return res.status(400).json({ body: 'Body must not be empty' });
  }
...
}

This is the index.js

"use strict";
const functions = require('firebase-functions');
const express = require('express');
const app = express();
const {createContact}= require('./handlers/contacts');

//middle ware 

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// server functions

app.post('/contact', createContact);

exports.api = functions.https.onRequest(app);

Thanks for your help

As you asked in question (req.body.body), You can do like this,

if (!(req.body.body || '').trim()) {   // ERROR HERE WHEN VALIDATING
    return res.status(400).json({ body: 'Body must not be empty' });
}

But If your request body is like this req.body, You can do like this,

if (!req.body || !Object.keys(req.body).length) { 
    return res.status(400).json({ body: 'Body must not be empty' });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM