Sandro Rey
Sandro Rey

Reputation: 2999

node js express cannot post - getting Cannot POST error message

I am new in nodeJS, I have created this application:

const express = require('express');
const app = express();

app.use (express.json());
app.post('api/hostels', (req, res) => {
    const hostel = {
        id : hostels.length + 1,
        name: req.body.name
    };
    hostels.push(hostel);
    res.send(hostel);
});

I send this body in the PostMan raw body (json)

{
    "id": "4",
    "name" : "new Request"
}

but I am getting this error:

 <body>
        <pre>Cannot POST /api/requests</pre>
    </body>

Upvotes: 0

Views: 5527

Answers (3)

Juhil Somaiya
Juhil Somaiya

Reputation: 953

Well, you did a small mistake while defining a route of the express. you have app.post('api/hostels', (req, res) => {}) instead you should have app.post('/api/hostels', (req, res) => {})

Upvotes: 2

ioedeveloper
ioedeveloper

Reputation: 538

You are posting to /api/requests, your endpoint shows /api/hostels. Change the endpoint on your postman to /api/hostels.

Upvotes: 0

Yash Shah
Yash Shah

Reputation: 125

There is a mistake in your post, theres a missing / in you app.post

it should be app.post('/api/hostels', (req, res) => { }

Upvotes: 0

Related Questions