Getting cannot POST / error in Express

marie picture marie · Feb 19, 2018 · Viewed 8.7k times · Source

I have a RESTful API that I am using postman to make a call to my route /websites. Whenever I make the call, postman says "Cannot POST /websites". I am trying to implement a job queue and I'm using Express, Kue(Redis) and MongoDB.

Here is my routes file:

'use strict';
module.exports = function(app) {
// Create a new website
const websites = require('./controllers/website.controller.js');
app.post('/websites', function(req, res) {
  const content = req.body;
  websites.create(content, (err) => {
    if (err) {
      return res.json({
        error: err,
        success: false,
        message: 'Could not create content',
      });
    } else {
      return res.json({
        error: null,
        success: true,
        message: 'Created a website!', content
      });
    }
  })
});
}

Here is the server file:

const express = require('express');
const bodyParser = require('body-parser');
const kue = require('kue');
const websites = require('./app/routes/website.routes.js')
kue.app.listen(3000);

var app = express();

const redis = require('redis');
const client = redis.createClient();
client.on('connect', () =>{
  console.log('Redis connection established');
})

app.use('/websites', websites);

I've never used Express and I have no idea what is going on here. Any amount of help would be great!! Thank you!

Answer

yBrodsky picture yBrodsky · Feb 19, 2018

The problem is how you are using the app.use and the app.post. You have.

app.use('/websites', websites);

And inside websites you have:

app.post('/websites', function....

So to reach that code you need to make a post to localhost:3000/websites/websites. What you need to do is simply remove the /websites from your routes.

//to reach here post to localhost:3000/websites
app.post('/' , function(req, res) {

});