In my experience, the GET request is functioning properly within Postman, but for some reason the POST method continues to send requests repeatedly

ISSUE: I am encountering a problem while making a POST request in Postman. The application keeps sending requests without receiving any response.

I have read through various solutions for Postman hanging during a POST request, but none of them seem to solve my specific problem.

GET REQUEST IS FUNCTIONING PROPERLY

https://i.stack.imgur.com/Yiugd.png

Below is the request that I submitted:

{
    "title": "This is title",
    "description":"This is my first RestfulAPI"
}

https://i.stack.imgur.com/DdhEW.png

I have three files named Post.js, posts.js, and app.js

Post.js

const mongoose = require('mongoose');
//Creating a schema
const PostSchema= mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    }
})
module.exports=mongoose.model('Posts',PostSchema);

posts.js

const express= require('express');
const router=express.Router();
const Post= require('../models/Post');
router.get('/',(req,res) => {
    res.send('We are on posts');
});

router.get('/specific',(req,res) => {
    res.send('Specific posts');
});

router.post('/',async (req,res)=>{
    console.log(req.body);
    const post= new Post({
        title: req.body.title,
        description: req.body.description
    });

    try{
        const savedPost = await post.save();
        res.json(savedPost).status(3000).end();
    }catch(err){
        res.json({message: err}).status(3000).end();
        console.log('Something is wrong');
    }
});

module.exports= router;

app.js

const express = require('express');
const mongoose= require('mongoose');
const app= express();
const bodyParser= require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());


const postsRoute = require('./routes/posts');
app.use('/posts',postsRoute);

app.get('/',(req,res) => {
    res.send('We are on home');
});


mongoose.connect(process.env.DB_CONNECTION,{ useNewUrlParser: true,useUnifiedTopology: true },() => 
    console.log('connected to DB!')
);
app.listen(3000);

The output on my console after sending the POST request https://i.stack.imgur.com/XMqEi.png

Answer №1

It's unnecessary to include .end() after using res.json(), as the intention is to return the data of savedPost to the client.

The express documentation states here that

[res.end()] is only used to abruptly end a response without sending any data. If data needs to be sent, methods such as res.send() or res.json() should be used instead.

When working with HTTP, it is important to include the appropriate HTTP status code ranging from 1xx to 5xx in your response. More information about these codes can be found here

Your response typically should resemble this:

res.status(200).json(savedPost);

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

``Change the color of the sections in a 3D pie chart on a Highcharts

I am looking to create a custom pie chart with two different colors: one for the main surface and another for the sides. Currently, I can only configure the lighter blue color for the main surface, but I would like to also change the darker blue color for ...

The submission of the form using AJAX is currently experiencing issues

My current issue involves ajax not functioning as intended. I have a form that is being submitted through ajax to my php file for the purpose of updating my database. The database update is successful, but there seems to be a problem with the ajax function ...

Tips for Customizing Dialogs with CSS Classes in mui5 Using Emotion/Styled

When attempting to customize the styling of a mui Dialog, I encountered an issue where it wouldn't accept className even when placed inside PaperProps. While inline styles worked, my preference was to import styles from a separate stylesheet named Sty ...

Using ValidationGroup to trigger JavaScript calls from controls

Is it possible to trigger a JavaScript function from the "onclientclick event" of a button that has a ValidationGroup assigned? <asp:Button ID="btnTest" runat="server" Text="Test" OnClick="btnTest_Click" ValidationGroup="Valid ...

Always display all options in MUI Autocomplete without any filtering

I am seeking to eliminate any filtering in the MUI Autocomplete component. My goal is for the text field popper to display all available options. The results are obtained from a server-side search engine. These results, or "hits," already provide a filter ...

What is the best way to arrange an array of objects based on a specific attribute?

Ordering object based on value: test": [{ "order_number": 3, }, { "order_number": 1, }] Is there a way to arrange this so that the object with order_number 1 appears first in the array? ...

Updating a div using PHP elements

Currently, I'm using a webcam to capture images for a project related to learning. My goal is to showcase the recently taken photos. After taking a photo, it gets stored in a folder. To display all the collected photos within a <div>, I need to ...

Is it possible to utilize a React component within the DataGrid cell instead of the standard cell types like 'string', 'number', 'date', and 'dateTime' in Material UI?

Using React, Material UI, and TypeScript I am trying to embed a React component into the cell of a DataGrid but have encountered an issue. I have explored custom column types for cells here, however, it only allows me to manage string formats, whereas I ...

Exploring the keyof operator in Typescript for object types

Is there a way to extract keys of type A and transfer them to type B? Even though I anticipate type B to be "x", it seems to also include "undefined". Why does the keyof operator incorporate undefined in the resulting type? It's perplexing. I kn ...

Troubleshooting: React Native and OneSignal notifications not showing up

Currently, I am developing an app in React Native and working on integrating notifications with OneSignal. Although I am able to efficiently receive notifications, I do not want them to be displayed on the screen when they are received. I came across a ` ...

I am attempting to incorporate an NPM package as a plugin in my Next.js application in order to prevent the occurrence of a "Module not found: Can't resolve 'child_process'" error

While I have developed nuxt apps in the past, I am new to next.js apps. In my current next.js project, I am encountering difficulties with implementing 'google-auth-library' within a component. Below is the code snippet for the troublesome compon ...

Develop a custom autocomplete feature using Formik in React for selecting values from an array of objects

Looking to Add Autocomplete Functionality in Your React Application Using Formik for Seamless Selection of Single and Multiple Values from an Array of Objects? Take a Look at this Code snippet! [see image below] (https://i.stack.imgur.com/ekkAi.png) arra ...

Ways to disable the ability to close a bootstrap modal by pressing the backspace key

How can I enable the backspace button in a Bootstrap Modal form for textboxes and textareas? $('body').keydown(function (e) { if ($('#myModal').is(':visible')) { if (e.keyCode == 8) { retu ...

Could an element's loading be postponed on the initial page a user lands on?

One of my clients has requested a live chat system to be added to their website. I am fully capable of implementing it, and it is included through a script tag. Additionally, they have asked for a slight delay before the chat system loads in. My initial t ...

Trigger Element Upon Click

Forgive me in advance for the lack of quality in this question, but I'll proceed anyway: All I want is for an element to slide open when clicked with a mouse! That's all! More specifically, I am looking for a single menu item that, upon clickin ...

Converting JSON data into a table using jQuery, with certain columns hidden from view

I am currently working on developing a mobile app using jQuery Mobile and JSON. I have encountered two separate questions: 1) I have a JSON data set which includes fields such as id, name, surname, point, and mail. In my table that lists this data, I init ...

Removing the JavaScript unicode character 8206 from a text string

I recently transitioned from VB.NET to JavaScript, and I am still getting familiar with the language. I have encountered an issue where a string I'm working with in JavaScript contains Unicode escape characters (0x5206, left-to-right mark) that I need ...

Issues with Displaying Components Generated from an Array in JSX

I have a task variable which has the structure as follows: [ team_id_1: { task_id_1: { description: ... }, task_id_2: { description: ... } }, team_id_2: { ... } ] When trying ...

Toggling javascript functionality based on media queries

On one of my slides, I want to display images that are specific to different devices like iPhone, iPad, and desktop. I am looking for a way to filter these images based on the device. Using display:none won't work as it's JavaScript, but here is ...

How is it possible for the output to be a string array when the variable was declared as a number in TypeScript?

Snippet: function sampleFunction(sample:string|number|string[]) { if(typeof sample == "string") { console.log("Sample is String " + sample); } else if(typeof sample == "number") { console.log("Sample is Number " + sampl ...