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

Recursive instruction malfunctioning

I'm currently trying to develop a custom recursion directive, but unfortunately it's not functioning as expected. I have followed the instructions outlined here: Recursion in Angular directives For reference, you can view the fiddle here: http ...

Manipulate documents in a Mongoose array by conditionally adding or removing elements

Upon receiving data from the front end, I am dealing with the following object: { name: "Test 1", sets: [1,2] } Mongo Schema: Sets name: { type: String }, tests : [{ type: Schema.Types.ObjectId, ref : 'Test' ...

Steps for returning a res.send(req.body) upon sending back to a function

I'm currently working on sending the req.body from a POST request route back to the executing function for further processing. The structure of req.body is as follows: { username: 'aa', password: 'ss' } After making the post requ ...

Unable to save the session identifier from the response headers while utilizing sessions in react/frappe framework

I am attempting to retrieve the session id (sid) from the response headers in a unique scenario. My client application is situated on a local environment, while my API is hosted on an ERP Next server. Upon sending a login request from the React app, I am ...

Creating a Yeoman application with a personalized Node.js server

As I embark on the journey of developing a node.js and angular application using the powerful Yeoman tool, I can't help but wonder about one thing. Upon generating my application, I noticed that there are predefined tasks for grunt, such as a server ...

The destruction of scope is not activated

Check out my issue in action with this plunkr demo. The problem I'm encountering is quite straightforward: manually calling $destroy or removing the element does not trigger the $destroy event. function link(scope, element, attrs) { // Manually ca ...

There was a parsing error due to encountering an unexpected reserved word 'interface' in the code, as flagged

I'm encountering an issue with my code when trying to utilize Props. The error message I'm receiving is "Parsing error: Unexpected reserved word 'interface'. (3:0)eslint". This project is being developed using next with TypeScript. Er ...

Having trouble getting the jquery ui datetimepicker to function properly in my node.js application using ejs and express

I am currently trying to implement the functionality found at this link: Below is an excerpt of my code: <html> <head> <script src="http://trentrichardson.com/examples/timepicker/js/jquery-1.7.1.min.js"> </script> < ...

Error occurs when attempting to instantiate a class with parameters that do not match any available constructor signatures

I am attempting to encapsulate each instance of router.navigateByUrl within a class function, with the intention of calling that function in the appropriate context. However, I am encountering an error that states 'Supplied parameters do not match any ...

Changing between two images using HTML and CSS

I am currently designing a WordPress theme and I would like to create an effect where two different thumbnail images switch on hover. The code that I have come up with so far looks something like this : <a class="thumb" href="posturl"> <img src= ...

What is the best way to set up the --public-host for operating an Angular universal app in conjunction with an Ngin

Looking to implement HMR for a universal app, I want to confirm if it is possible. I have successfully set up and run an Angular 8 application using the default "ng new" command. To run it behind a reverse proxy, I modified npm start as follows: e.g. { " ...

Trouble with Chakra UI loading Images from local sources

I'm running into issues when trying to load local images using the Chakra UI library in combination with Next.js. <Image src="./homepage/footer/Black.svg" /> Here is the current folder structure: When checking my console, I see the f ...

Is there a way to determine the dimensions of the DOCUMENT using Javascript instead of the VIEWPORT?

To ensure clarity, let me explain the distinctions between document, window, and viewport.... WINDOW refers to the entire browser window, including all navigation bars, etc.... VIEWPORT is the section of the window used to view the current XHTML/HTML/Fla ...

Testing Async operations in the browser with Mocha and Chai

I'm having trouble running async tests with mocha. Below is the snippet of my code: describe('Brightcove Wrapper',function(){ describe("#init()", function() { it("Should inject the brightcove javascript", function(callback){ ...

What is the best choice for organizing a RESTful design of a limited, disordered collection: Map

My colleague and I are currently engaged in a lively discussion about the structure of a REST service. When it comes to our API, most GET calls to collections follow this format: GET /resource [ { "id": 1, ... }, { "id": 2, ... }, { "id": 3, . ...

Divide Angular ngFor into separate divs

Here is an example of my current array: [a, b, c, d, e, f, g, h, i] I am aiming to iterate through it using ngFor and split it into groups of 3 elements. The desired output should look like this: <div class="wrapper"> <div class="main"> ...

Is there a way to conceal a component using Twitter Bootstrap while having the ability to reveal it with the help of

Suppose I generate an HTML element in the following manner, <div id="unique-div" class="concealed">Hello, TB3</div> <div id="unique-div" class="hide-me">Greetings, TB4</div> <div id="u ...

Fetch a document from a NodeJS Server utilizing Express

Is there a way to download a file from my server to my machine by accessing a page on a nodeJS server? I am currently using ExpressJS and I have attempted the following: app.get('/download', function(req, res){ var file = fs.readFileSync(__d ...

What methods should I use to modify the upcoming array of objects?

I have been struggling with this exercise for about an hour now, and I can't figure it out. Can someone please help me with this? Here is the array that I retrieved from the database: View Base Array Image let data = [ { "name": "October : 2019", "u ...

Accessing a dynamic property within an array of objects in Mongo/Mongoose: A complete guide

When using the $in operator within a condition, I am able to make it work by hard coding the property that I am searching for. However, I am unsure of how to handle this if the property is dynamic (I am iterating over an object where the key's value i ...