-1

I'm created a simple api, for this I'm using node.js + express. Also I'm using body-parser. But when I try to get req.body I get undefined. Here is my app.js:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = express.Router();
const port = process.env.PORT || 8080;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', function (req, res) {
  res.status(200).send('API works.');
});

var AuthController = require('./auth/authController.js');
app.use('/api/auth', AuthController);

And my authController.js:

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
var jwt = require('jsonwebtoken');
const config = require('../config');
const connection = require('./../db/db_config');
var VerifyToken = require('./verifyToken');


router.post('/authenticate', function(req, res) {
  let phone = req.body.phone;
  console.log(phone)
});

And phone is always undefined. What's wrong with my code. Please help me

testivanivan
  • 967
  • 13
  • 36

1 Answers1

0

I build an example on using body-parser for you:

const express = require("express");
const app = express();

const bodyParser = require("body-parser");
var jsonParser = bodyParser.json();

app.listen(5000, function () {
    console.log("listening on 5000");
  });

app.post("/add/", jsonParser, function (req, res) {
  let exampleObject = {
    id: 1,
    example: req.body.example
  };
  res.status(200).json(exampleObject);
});

Reis
  • 101
  • 2
  • 7