【问题标题】:How to send the Response the request Post to save on database? NodeJs?如何发送响应请求帖子以保存在数据库中?节点?
【发布时间】:2018-06-07 02:10:05
【问题描述】:

我正在使用 Postaxios.jsnode.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))
  }

}

my方法的结果post

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..内。

【问题讨论】:

  • 问题是什么?
  • 我想知道如何保存到数据库。
  • 如果您调用 dao.post 可能您应该将数据对象作为参数传递,然后将此对象作为第二个参数传递给 axios.post。什么是teste的方法?
  • 你可以告诉我,怎么样?请问?

标签: javascript node.js reactjs axios


【解决方案1】:

根据 POST 方法中的https://github.com/axios/axios 文档,您应该将第二个参数作为请求正文传递。就像在你的函数 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;

道:

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))
    }
}

【讨论】:

  • 你有什么错误吗?你的请求成功了吗?您是否在后端获取数据?
  • 是的,成功了。但数据不会进入数据库。
  • 在控制台中,出现data 但我刷新数据库但它是空的:(
  • 在数据库和 UI 之间有 backand。可能是BE的问题。能提供BE功能吗?
  • 请提供文件轮播我不能说这个例子有什么问题。请求数据库和 POST 处理程序的 BE 代码在哪里?
猜你喜欢
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
  • 2021-04-07
  • 2021-05-09
  • 1970-01-01
相关资源
最近更新 更多