Как отправить ответ на запрос Post для сохранения в базе данных?NodeJs? - PullRequest
0 голосов
/ 06 июня 2018

Я делаю метод Post с axios.js и node.js, и он работает.Это делает запрос, но запрос не сохраняет данные в базу данных.

Мой axios.js, где я делаю запрос:

teste = () => {
  axios.post('/api/post', {
      firstName: 'Marlon',
      lastName: 'Bernardes'
    })
    .then(function(response) {
      console.log(response)
    });
}

Мой маршрут post:

const express = require('express');
const dao = require('../matchs-dao.js');
const router = express.Router();

router.post('/post', async(req, res) => {
  const response = await dao.post();
  res.send(
    response
  )
});

module.exports = router;

Мой маршрутный пост ждут DAO, посмотрите его:

const axios = require('axios');

module.exports = {
  post() {
    return axios.post('http://localhost:3004/score')
      .then(response =>
        response.data)
      .catch(error => console.log(error))
  }

}

Результат моего метода post enter image description here

Server.js:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const rotas = require('./rotas')
const port = 3001;

app.use(bodyParser());

app.get('/', (req, res) => {
  res.send("was")
});

app.use('/api', rotas);

app.listen(port, () => {
  console.log('Server rodando na porta 3001')
})

Маршрут post находится внутри /api ..

1 Ответ

0 голосов
/ 06 июня 2018

Согласно документации https://github.com/axios/axios в методе POST, вы должны передать второй параметр в качестве тела запроса.Как в вашей функции teste.

Маршрутизатор:

const express = require('express');
const dao = require('../matchs-dao.js');
const router = express.Router();

router.post('/post', async(req, res) => {
    const response = await dao.post(dataObject);
    res.send(response)
});

module.exports = router;

DAO:

const axios = require('axios');

module.exports = {
    post(data) {
        return axios.post('http://localhost:3004/score', data)
            .then(response => response.data)
            .catch(error => console.log(error))
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...