R
R
Ruslan Zolotarev2020-08-02 15:01:47
MongoDB
Ruslan Zolotarev, 2020-08-02 15:01:47

Axios post request to the node js server goes through and enters data into the database, but fails with a 503 error, what should I do?

In general, an application with a stack Front: React, Redux, Redux-thunk, Typescript, axios Back: Nodejs, MongodbAtlas. The problem is that when sending a POST request to the server, the request hangs for a minute, then either the 503 server unavailable error or 500 comes from the server. Before putting all this on heroku, it gave 500. The whole trick is that the request passes and in the end, Node enters the data into the database as expected, but still returns an error.

At the same time, a GET request to /api/users/ goes through and gets users absolutely adequately.

Data access layer level with axios request (here, instead of localhost, the application address should be ...com):

import * as axios from 'axios';

const instance = axios.create({
  baseURL: 'http://localhost:5000/api/',
});

export const usersAPI = {
  getUsers() {
    return instance.get('users/').then(res => res.data);
  },
  addUser(data) {
    return instance
      .post('users/add', data)
      .then(res => console.log(res.data))
      .catch(error => console.log(error));
  },
};


Actions in which a request is called to the server and subsequent entry into the editor:
export const actions = {
  setUsers: (users: Array<IUserServerType>) => ({ type: 'SET-USERS', users } as ISetUsersAction),
  addUser: (user: IUserServerType) => ({ type: 'ADD-USER', user } as IAddUserAction),
};

export const getUsers = () => async (dispatch: Dispatch<ISetUsersAction>) => {
  const users = await usersAPI.getUsers();
  dispatch(actions.setUsers(users));
};


The app.js file is the server entry point:
const express = require('express');
const path = require('path');
const config = require('./config');
const mongoose = require('mongoose');

const app = express();

app.use(express.json({ extended: true }));

let userRoutes = require('./routes/users.routes');

app.use('/api/users', userRoutes);

if (process.env.NODE_ENV === 'production') {
  app.use('/', express.static(path.join(__dirname, 'client', 'build')));

  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
  });
}

const PORT = config.PORT || 5000;

async function start() {
  try {
    await mongoose.connect(config.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
    });
    app.listen(PORT, () => console.log(`App has been started on port ${PORT}!`));
  } catch (e) {
    console.log('Server error', e.message);
    process.exit(1);
  }
}

start();


Processing Router:
const { Router } = require('express');
const { check, validationResult } = require('express-validator');
const User = require('../models/User');
const router = Router();

router.post(
  '/add',
  [
    check('first_name').notEmpty(),
    check('last_name').notEmpty(),
    check('email', 'Некорректный email').isEmail(),
  ],
  async (req, res) => {
    try {
      const errors = validationResult(req);

      if (!errors.isEmpty()) {
        return res.status(400).json({
          errors: errors.array(),
          message: 'Данные введены некорректно',
        });
      }

      const { first_name, last_name, email } = req.body;

      const user = new User({ first_name, last_name, email });

      await user.save();

      res.status(201);
    } catch (e) {
      res.status(500).json({ message: 'Что-то пошло не так, попробуйте снова' });
    }
  },
);

router.get('/', async (req, res) => {
  try {
    const users = await User.find({});
    res.json(users);
  } catch (e) {
    res.status(500).json({ message: 'Что-то пошло не так, попробуйте снова' });
  }
});

module.exports = router;


Here is a link to the github, if it's more convenient: https://github.com/NextLint/test

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Nedzvetsky, 2020-08-02
@ProGatti

Instead
of res.status(201);
do
res.status(201).end();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question