Jo Ko Jo Ko - 3 months ago 7
Javascript Question

Why isn't Node.js Express with MongoDB responding to fetch API calls (ReactJS and Redux)?

Using ReactJS, Redux, Webpack, Node.js and Express with MongoDB, I am following the tutorial https://github.com/vasansr/mern-es6 and trying to integrate it into my project. First, I am trying to make a POST request to the server I created. And it gets a response with a success and no error is logged. Yet inside the server POST API, it does not log

console.log('Req body', req.body);
, and in terminal I checked to see if the database has been created with
mongo -> show dbs
but it is empty.

Could it be that something is intercepting the request from the server? What could be the issue?

Answer

This...

app.use('/', function (req, res) {
  res.sendFile(path.resolve('client/index.html'));
});

comes before:

app.post('/api/users/', function(req, res) {
  //...
});

Since it's app.use the POST /api/users will still hit that middleware, and res.sendFile ends the request/response. You'll probably see that your post is getting back the client HTML.

Try moving your client HTML endpoint to the end of your middleware, just before the error handlers if you have them. That way, it'll only get used if none of your API endpoints match. Or if you want just GET / to return the HTML, change use to get:

app.use(webpackDevMiddleware(compiler, {noInfo: true, publicPath: config.output.publicPath}));

app.use(webpackHotMiddleware(compiler));

app.use(express.static('dist')); //where bundle.js is

app.use(bodyParser.json());

app.post('/api/users/', function(req, res) {
  console.log('Req body', req.body);
  var newUser = req.body;
  db.collection('users').insertOne(newUser, function(err, result) {
    if(err) console.log(err);
    var newId = result.insertedId;

    db.collection('users').find({_id: newId}).next(function(err, doc) {
      if(err) console.log(err);
      res.json(doc);
    });
  });
});

app.get('/', function (req, res) {
  res.sendFile(path.resolve('client/index.html'));
});