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}`);
});