0

Making a typescript API, my request body is coming undefined when i try to use the default parser from express, such as:

import express from 'express';
import { router } from './routes';

const app = express();
const port = 3000;

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

app.listen(port, () => {
  console.log(`App rodando na porta: ${port}`);
});

If i use the lib "body-parser" and use it as a middleware in my post routes, i can get the expected result, but as it is deprecated, i dont want to use it.

Do you guys know of a way that i can make that work better?

My route:

// import bodyParser from 'body-parser';
import express from 'express';
import { createUserService } from '../service';

export const router = express.Router();

router.post('/users', async (req, res) => {
  try {
    const { name, email, password } = req.body;
    await createUserService({ name, email, password });
    res.status(201).send({ name, email, password }).status(201);
  } catch (error) {
    res.status(400).send({ error: error.message });
  }
});

UPDATE!!!!:

My problem was trying to use the express middlewares in my app folder instead of my actual router.

That way it works:

import express from 'express';
import { createUserService } from '../service';

const router = express.Router();

router.use(express.json());
router.use(express.urlencoded({ extended: true }));

router.post('/users', async (req, res) => {
  try {
    const { name, email, password } = req.body;
    await createUserService({ name, email, password });
    res.status(201).send({ name, email, password }).status(201);
  } catch (error) {
    res.status(400).send({ error: error.message });
  }
});

export { router };

And my app just calls for my router that has all of its middlewares:

import express from 'express';
import { router } from './routes';

const app = express();
const port = 3000;

app.use(router);
app.listen(port, () => {
  console.log(`App rodando na porta: ${port}`);
});
Diego
  • 67
  • 7
  • 1
    move ```app.use(router); app.use(express.json()); app.use(express.urlencoded({ extended: true }));``` after the imports and try it that way. – ZombieChowder Sep 12 '21 at 14:41
  • https://stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4 – mohammad Naimi Sep 12 '21 at 14:41
  • @mohammadNaimi They actually brought back the `express.json(...)` function. – Tyler2P Sep 12 '21 at 14:45
  • @ZombieChowder moving the imports didnt help, but you gave me an idea that i just edited in the question. thank for those who helped. – Diego Sep 12 '21 at 15:08

0 Answers0