What is the best way to structure my POST data when conducting tests on an express API endpoint?

I have been exploring the MERN stack with the help of this guide: https://www.digitalocean.com/community/tutorials/getting-started-with-the-mern-stack.

Currently, I am trying to test a POST API endpoint that is built using express.

The node server is up and running, and I am utilizing Postman to check the functionality of the endpoint.

However, I am facing challenges in formatting the post data properly, as my POST requests are returning errors when sent.

Below is an overview of my API:

const express = require ('express');
const router = express.Router();
const Todo = require('../models/todo');

router.get('/todos', (req, res, next) => {

  //this will return all the data, exposing only the id and action field to the client
  Todo.find({}, 'action')
    .then(data => res.json(data))
    .catch(next)
});

router.post('/todos', (req, res, next) => {
  if(req.body.action){
    Todo.create(req.body)
      .then(data => res.json(data))
      .catch(next)
  }else {
    res.json({
      error: "The input field is empty"
    })
  }
});

router.delete('/todos/:id', (req, res, next) => {
  Todo.findOneAndDelete({"_id": req.params.id})
    .then(data => res.json(data))
    .catch(next)
})

module.exports = router;

Here is my Schema structure:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

//create schema for todo
const TodoSchema = new Schema({
  action: {
    type: String,
    required: [true, 'The todo text field is required']
  }
})

//create model for todo
const Todo = mongoose.model('todo', TodoSchema);

module.exports = Todo;

While testing with Postman, my URL is "http://localhost:5000/api/todos", and the request body consists of key-value pairs where the key is "action" and the value is "asdf". The result of sending this data is:

{
    "error": "The input field is empty"
}

I am seeking guidance on how to correctly format the body data in order to successfully test my POST endpoint. Any assistance would be greatly appreciated!

Answer №1

  1. To get started, launch Postman and choose the POST request, then navigate to Body.

  2. In the Body section, opt for raw and input your data as shown below, changing the format from text to JSON:

    { "action":"asdf" }

  3. Remember to include this code snippet in your app.js file above any route handlers:

    const app = express(); app.use(express.json());

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

Independent Dropbox Collections

Query: function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var colCount = table.rows[0].cells.length; for (var i = 0; i < colCount; i++) { var ...

Fetching data from a server using React's axios library

I've been working on a personal project and ran into an issue. I'm trying to fetch all the car data from my database using Reactjs and Axios. While I can see all the data in the console, my page remains blank. It's worth mentioning that I&ap ...

Is there a way to load all movies in advance when none of the tags are selected?

In my current project, I am working on a feature that involves an array of movie objects. Each movie has a name and tags assigned to it. I want to be able to display movies based on the tags selected by the user. For example, if the user selects the tag "c ...

The jQuery scripts are having trouble cooperating

Currently, I am in the process of developing a website. The main focus at the moment is on creating a responsive menu and incorporating jQuery scripts. However, I seem to be facing some challenges in getting everything to work seamlessly together. Each scr ...

How to detach functions in JavaScript while preserving their context?

Can functions in JavaScript be detached while still retaining access to their context? For instance, let's say we have an instance of ViewportScroller called vc. We can retrieve the current scroll position with the following method: vc.getScrollPosi ...

Integrating Asp.Net Core for server-side functionality with React for client-side interactions

I have started a simple Asp.Net default project in Visual Studio 2015 using the template: ASP.NET Core Web Application (.NET Core) / Web Application, No Authentication. Following that, I created a package.json file to load all the necessary packages for R ...

The child div can be scrolled horizontally, while the parent window remains fixed

I am facing a challenge with my HTML and CSS setup. I want to create a child div that scrolls horizontally, but I do not want the parent window to scroll along with it. Below is my current code: <div id="parent"> <div id="div1"> . ...

Ajax response values overlap

I am developing an application that requires multiple Ajax requests, but I encountered a problem where I am receiving the same response values for both requests. Each request must include a data field called activityCode, yet I keep getting the value of Sc ...

Obtain image from an external server using AJAX

Our team is currently working on retrieving images from external servers that are cross-origin. While JSONP may not be effective in this case, we are exploring the use of plain AJAX GET requests. One potential workaround involves using iframes to manipulat ...

Occasionally, the map may take a moment to fully load

Update: Resolving the issue involved directly calling these two methods on the map object: leafletData.getMap().then(function(map) { map.invalidateSize(); map._onResize(); }); Encountering a minor yet bothersome problem with the Leaflet directive ...

Enhancing TypeScript type definitions for the Response.render() method in Express

Struggling with enhancing the type safety of my Express project by extending the Response.render function. import { Response } from "express"; import { Product } from "../models/Product.interface"; export interface ProductListResponse ...

Steps to display a JSX component stored in a variable

Presently, I am implementing an if/else statement within my code to determine the content that will be displayed in the JSX element named 'signupMessage'. Subsequently, I render the contents of this 'signupMessage' element. render() { ...

Converting JSON data into an HTML table

I'm struggling to convert a JSON object into an HTML table, but I can't seem to nail the format. DESIRED TABLE FORMAT: Last Year This Year Future Years 45423 36721 873409 CURRENT TABLE FORMAT: Last Year 45423 This ...

Adjust the background color of children based on the parent's mouseover event

Seeking a solution to fill three bars with varying percentages: <div class="bars" style="width:0%; background-color: red;"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </ ...

Filtering with AngularJS based on integer comparison will assist in stream

Currently, I have implemented a "price" field on my website using the JQuery-UI slider. This field comprises of two integer values: minPrice and maxPrice. Suppose I possess an array of objects structured in this manner: objarr=[ { 'name'=&ap ...

Using a constructor function in a for loop

Currently, I am learning how to build a Blackjack game with Javascript on Codecademy. I'm struggling to figure out what code to write inside the for-loop. The task at hand is to create a "score" method within the Hand constructor. This method should ...

What steps can I take to allow a third-party JavaScript to access my TypeScript object?

I am working on an Angular application and I have a requirement to develop an API for a third-party JavaScript that will be injected dynamically. public class MyApi{ public callSomeFunction():void{...} public getSomeValue():any {...} } var publicA ...

Difficulty encountered while deploying a React application on Netlify

I followed the instructions on a Medium link to deploy my React application on Netlify: To set up the production mode, I utilized an express server for defining build scripts. After creating the build scripts on my local machine, I uploaded them to the Ne ...

Can anyone recommend a high-quality jQuery lightbox replica?

Key Features Needed: Customizable with CSS Capable of handling forms, not just images Extensively documented Please provide any recommendations and suggestions for suitable options. Thank you in advance ...

Angular 16 SSR encounters a TypeError when the 'instanceof' operator is used on a value that is not an object

I have been facing an issue while updating my Angular application from version 15 to 16. Everything seems to work fine with Angular, including building for Angular Universal without any errors. However, when I attempt to serve using npm run serve:ssr, it t ...