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

Making an Ajax request from within an iframe using the easyXDM framework

I am currently utilizing easyXDM for enhancing the communication between a website and a shopping cart embedded within an iframe on my domain. Whenever a user adds an item to the shopping cart, I utilize easyXDM.Rpc to transmit the item details to the ifra ...

Exploring methods for handling svgs incorporated in angular.js templates with webpack

I'm currently working on cache-busting my SVGs and other files like translation JSON. The issue I'm facing is that webpack does not seem to recognize imported svgs in the following format: <md-icon md-svg-src="assets/icons/ic-edit.svg">&l ...

Why am I getting the error "TypeError: Object(...) is not a function" when attempting to integrate Vanilla Tilt with React?

Looking for assistance on implementing Vanilla Tilt in my React application, I have referenced the following example: https://codesandbox.io/s/vanilla-tilt-with-react-n5ptm The code snippet I am working with is as follows: import React, { Component, useEf ...

Error: Chrome is preventing an AJAX request

Hello everyone, I have been facing an interesting issue with my Ajax request. It seems to work perfectly fine in Internet Explorer, which is quite surprising. However, when I attempt to run the same code in Chrome, I encounter the following error: XMLHt ...

Is it not possible to use GLOB with JSHint on Windows operating systems?

Currently, I am experimenting with using NPM as a build tool (). My experience with NPM is limited, and at the moment I only have JSHint and Mocha installed. Attached is my package.json file. However, when I try to run "npm run lint" in the Windows 7 comma ...

Creating a default menu within a specific route in Ember.js is a crucial step in

I have created a JSBin code for my Ember.js application which can be found here: When I click on Item A, I want the ABCD menu on the left to remain visible and not disappear. Thank you. ...

Load custom JS with Google

I have integrated the Google Ajax API and now I need to load custom javascript that relies on the libraries loaded by the ajaxapi. What is the best way to accomplish this? ...

Is there a way to access fields from an associated model within React components?

Is there a way to access fields from an associated model in React components within Rails? I have a listing model that I'm iterating through in a React component and retrieving all the fields for each record, including the ID of the associated model. ...

Using Reactjs to bind onClick event to a list component generated dynamically

If I have a render function that resembles the following: render() { var user_rows = [] this.state.user_list.forEach((user, index) => { user_rows.push( <tr key={user}> <td><div className="bt ...

Organize and categorize items

I need help sorting an object displayed below. My goal is to calculate the sum of all rating properties for each object, and then sort the objects based on the highest total rating. For instance, if the total rating for Intro 1 is 7 and for Intro 2 is 3, ...

What role does @next/react-dev-overlay serve in development processes?

Currently, I am diving into a NextJs project. Within the next.config.js file, there is this code snippet: const withTM = require('next-transpile-modules')([ 'some package', 'some package', 'emittery', ...

The parameter type 'router' cannot be replaced with the type 'typeof ...'. The 'param' property is not included in the type 'typeof'

I'm currently working on a node application using TypeScript and have set up routing in a separate file named 'route.ts' import home = require('../controller/homeController'); import express = require('express'); let ro ...

Unable to resolve the issue of Duplicate keys detected with value '0'. This could potentially lead to errors during updates

Encountered a warning in Vue js stating 'Duplicate keys detected: '0'. This warning could potentially lead to an update error. To resolve this issue, I utilized the getter and setter in the computed variable and dispatched the value to Vuex ...

Disable the resizing and responsiveness features in the jQuery Basic Slider

I'm currently utilizing the Basic jQuery Slider from the Basic Slider website, and I am attempting to eliminate the responsive/resize feature. My goal is to keep the slider contained within a centered div without changing its size. However, whenever I ...

Enter a keyword in the search bar to find what you're looking

I am working on a form where users can select their occupation from a list that is stored in a separate .js file. The list includes various occupations like 'AA Patrolman' and 'Abattoir Inspector'. var occupationSelect = "<select id ...

How to insert an image into a placeholder in an .hbs Ember template file

I'm looking to enhance a .hbs template file in ember by incorporating an image. I am not a developer, but I'm attempting to customize the basic todo list app. <section class='todoapp'> <header id='header'> & ...

Implement the callback-console.log feature from the epic-games-api into an Express.js application

Looking to integrate Epic Games output into an Express.js GET request but don't have any JavaScript experience, so go easy on me! XD const EpicGamesAPI = require('epicgames-status'); const express = require('express') const app = ...

Struggling to retrieve JSON data from the MercadoLibre API while consistently encountering the CORS error?

I have been attempting to access a mercadolibre API that provides JSON data I need to utilize. However, whenever I make an AJAX GET request, I keep receiving the same error: "Response to preflight request doesn't pass access control check: It does n ...

Enhancing the accessibility of Material UI Autocomplete through a Custom ListboxComponent

I have developed a custom ListboxComponent for the MUI Autocomplete component in MUI v4. How can I ensure that it meets the necessary accessibility requirements, such as navigating through options using the arrow keys? <Autocomplete ListboxComponent ...

Unlock the Full Potential: Enabling Javascript's Superpowers through PHP Execution

I specialize in PHP and JavaScript. Currently, I am attempting to incorporate JavaScript functionalities into my PHP code. However, I am encountering an issue where the code is not functioning properly. The PHP code that executes the JavaScript code is as ...