Home > database >  How to get req.body data using TypeScript, Express and Node with Routes in different files
How to get req.body data using TypeScript, Express and Node with Routes in different files

Time:04-10

I have been trying to answer this for days, searched through stackoverflow, the web and even rebuilt this multiple times.

I am trying to setup an express app using TypeScript to create a RESTApi, and I would like to keep my routes and controllers in separate files so I can have it organized.

I am open to other suggestions if this isn't the be best way.

The problem I am having is that if I output req.body it spits out the JSON that was sent but if I try to access req.body['order_key'] or req.body.order_key we get undefined

What am I doing wrong? :)

index.ts

import * as functions from 'firebase-functions';
import express from 'express';
// import * as bodyParser from 'body-parser';
import orderRoutes from './routes/orderRoutes';
// import {getAllOrders, updateOrder} from './orderController';

const app = express();

app.use(express.json());
// app.use(bodyParser.json()); // tried
// app.use(bodyParser.urlencoded({ extended: true })); // tried
app.use(express.urlencoded({extended: true}));

app.use('/orders', orderRoutes);

app.get('/', (req, res) => res.status(200).send('Hey there!'));

// handle orders
// app.get('/orders', getAllOrders);
// app.post('/orders', updateOrder);

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

I have tried to use bodyParser, the built in parser, all parser to get this to work

orderRoutes.ts

import {Router} from 'express';
import {getAllOrders, updateOrder} from '../controllers/orderController';
// eslint-disable-next-line new-cap
const router = Router();

router.route('/').post(updateOrder);
router.route('/').get(getAllOrders);

export default router;

orderController.ts

import {Request, Response} from 'express';

const getAllOrders = (req: Request, res: Response) => {
  res.status(200).send({
    status: 'success',
    message: 'Welcome',
  });
};

const updateOrder = async (req: Request, res: Response) => {
  res.status(200).send({
    status: 'success',
    message: 'Order created',
    data: 'data '   req.body['order_key']   req.body.order_key, // THIS IS THE ISSUE COMES UP UNDEFINED
  });
};

export {getAllOrders, updateOrder};

All the other routes work, here is the payload I am sending:

[
    {
        "id": 26442,
        "parent_id": 0,
        "customer_id": 1489,
        "order_key": "wc_order_DQSfOIyzobd4k"
    }
]

Using postman and I have it to RAW and with JSON on, screenshots below

Post issue

Post issue

Headers

Headers

Any help appreciated

CodePudding user response:

Well, your payload is an array with one object in it. As you show:

[
    {
        "id": 26442,
        "parent_id": 0,
        "customer_id": 1489,
        "order_key": "wc_order_DQSfOIyzobd4k"
    }
]

The brackets at the beginning and end indicate an array. If you really intend for the payload to be an array, then you would need to use req.body[0] to access the first object in that array.

Or, req.body[0].order_key to get the key.

Or, if you want to process more than one object (if there is more than one in the array), then you would use a for loop to loop over the objects in the array.


Or, if the API is really just supposed to be sent one object, then fix the client-side so you're sending the JSON version of just a single object:

{
    "id": 26442,
    "parent_id": 0,
    "customer_id": 1489,
    "order_key": "wc_order_DQSfOIyzobd4k"
}
  • Related