Post Request to Express API does not produce any output

Today, I encountered an issue while trying to create a JWT authentication API in Express. When I send a POST request with Postman, it only returns {}.

Below is the code for server.js:


const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const app = express();
const auth = require("./rutas/auth");
dotenv.config();
const port = process.env.PORT || 5000;
mongoose.connect(process.env.URI, {
  useUnifiedTopology: true,
  useNewUrlParser: true
});
app.use(express.json());
app.use("/api/auth", auth);

app.listen(port, () => {
  console.log(`Connected on port ${port}`);
});

And here is the code for auth.js where the POST request returns {}:


const express = require("express");
const { check, validationResult } = require("express-validator");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../modelos/User");

router.get("/", async (req, res) => {
  const usuarios = await User.find();
  res.send(usuarios);
});

router.post("/sign", async (req, res) => {
  const { nombre, email, contraseña } = req.body;
  res.json(req.body);
  console.log(req.body);
});

router.post("/login", [], async (req, res) => {
  const { email, contraseña } = req.body;
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() });
  }

  try {
    const usuario = await User.findOne({ email });
    const isValido = await bcrypt.compare(contraseña, usuario.contraseña);
    if (isValido) {
      const payload = {
        id: usuario._id
      };
      const token = jwt.sign(payload, "secretomagico", { expiresIn: "1h" });
      req.header("auth-token", token);
      res.send("In DB");
    }
  } catch (error) {}
});

module.exports = router;

I also provided the JSON message sent via Postman:

{ "nombre":"Jack", "contraseña":12345678, "email":"[email protected]" }

Answer №1

If you encounter a similar issue, remember to include the Content-Type: application/json in the header section of Postman. I mistakenly had Content-Type: application/x-www-form-urlencoded along with the correct one mentioned previously.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with rendering Html Element on FireFox compared to Chrome

Having some trouble with an individual component (a simple dropzone) while testing on Firefox. It seems to work fine on Chrome, and the CSS looks good. Css .container { position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); wi ...

Can you explain the distinction between 'rxjs/operators' and 'rxjs/internal/operators'?

When working on an Angular project, I often need to import functionalities like the Observable or switchMap operator. In such cases, there are two options available: import { switchMap } from 'rxjs/operators'; or import { switchMap } from ' ...

inserting a for-loop inside a div tag

I've created a script that modifies the background color and plays a sound in response to user input. The changes are triggered by the length of the input provided. Additionally, I have a div element where I aim to display the specific letter causing ...

Is an XMLHttpRequest necessary for updating a JSON file value using JavaScript?

Currently, I am working on a game feature that allows users to change their display name and then save it in a JSON file for easy access across different files and pages. I initially included an XMLHttpRequest in my code, but after stumbling upon this insi ...

Utilizing vanilla JavaScript or ES6 to extract data from a JSON file

I am currently working on an HTML project where I need to extract data from a JSON file that cannot be modified. I am looking to accomplish this using pure JavaScript or ES6, but I am struggling to make it work. Specifically, I am trying to retrieve a link ...

In React Native, changing the translation of an element causes it to shift below all other elements, regardless of

Check out this sandbox project: I'm trying to create a simple animation using translation in React Native, but I'm facing an issue where when I move the element to the right and down, it goes under other elements. However, if I move it left and ...

Using JavaScript to call a PHP file as the source file

I'm curious about the scenario where a .php file is called as a javascript. What does this signify and in what situations would it be necessary to use such an approach? Example: <head> <script src="dir/myphpfile.php" type="text/javascript" ...

How can one element be made to rely on the presence of another element?

I'm currently working on my portfolio website and encountering an issue. Whenever I hover over an image of a project, the image expands in size, becomes less transparent, and a description of the project pops up. However, I would like to include a lin ...

What steps can I take to streamline this code and enhance its elegance in writing?

Working on some practice problems involving higher-order functions, I managed to solve this particular problem. However, the code I used feels somewhat messy and not as elegant as it could be. Is there a better way to combine map and reduce for a cleaner s ...

What causes index.html to be returned instead of app.css?

I deploy my Angular application using an express server. var express = require('express'); var server = express(); server.use(express.static('./app')); server.all('*', function(req, res) { res.sendFile('index.html&apos ...

The primary directory specified in the package.json file

Question: I have a pre-existing library that I want to turn into an NPM module. Currently, the library is being required through the local file system. How can I specify the main directory path for my module's files? If my structure looks like this: ...

The console object in Chrome_browser is a powerful tool for debugging and

Having difficulty saving an amchart graph to the localstorage and retrieving the data successfully. https://i.stack.imgur.com/lJ3bJ.png In the original object, there is a mystery b, while in the new object, it appears as a normal object. In Internet Expl ...

React: The peculiar contradiction of useEffect with eventHandler props

Having trouble with this specific example. The issue arises with an Input component that includes an onChange prop to manage internal data changes. Under normal circumstances, if the value is updated externally, the onChange prop does not trigger since t ...

Navigable MEAN.js paths for CRUD operations

Exploring the world of MEAN stack with mean.js as my structure framework. Playing around with Express and Angular routing to understand how it all works. Here's one of my server routes: app.route('/api/projects/:projectId') .get(users. ...

Content briefly appears and then vanishes with the use of ng-if

On my webpage, I have content that is enclosed in an ng-if directive as shown below: <div ng-if="ShowMessgae" class="text-danger"> <p> <strong> Message displayed to User </strong> </p> < ...

Creating a JQuery slider that efficiently loads and displays groups of elements consecutively

Currently, I am in the process of developing an infinite horizontal tab slider using jQuery. My main objective is to optimize loading time by having the slider display only the first 10 slides upon initial page load. Subsequent slides will be loaded as the ...

Complete and automatically submit a form in a view using AngularJS

I have developed a basic AngularJS application that is functioning smoothly. Currently, I am looking to populate certain fields and submit the form directly from the view without requiring any user input. Below, you'll find some simplified JavaScrip ...

The for loop does not pause until the ajax response is received

When I enter the for loop, an ajax call is made. However, the for loop does not wait for the ajax call to receive a response before incrementing the value, causing the response to update to the wrong div element. For example: Let's say we have ' ...

Error encountered while compiling ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js

I've encountered a frustrating error message: Failed to compile ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'E:\IT&bsol ...

Unable to pass the jQuery value - troubleshooting tips for Laravel

JavaScript Issue return response()->json([ 'category' => $category, 'editRoute' => $artistCategoriesEditRoute ]); AJAX Response category Object { id: 1, title: "tt", parent_id: 0, … } id ...