javascript - 无法在 React 中将数据发布到 mlab

标签 javascript node.js reactjs mongodb express

我有一个内容可编辑的简单 div,我通过 onclick 事件获取用户在该 div 中输入的任何内容。我想将该数据发送到我在 Mlab 中的数据库,我在 Heroku 上托管我的应用程序。目前,当我尝试发布数据时,出现 404 错误,几秒钟后我得到 GET http://localhost:3000/static/js/0.chunk.js net::ERR_CONNECTION_REFUSED 我不知道为什么,因为我可以通过 get 请求检索已经存在的数据。我在这里做错了什么,我怎样才能成功发出那个帖子请求?这是我的组件:

import React, { Component } from 'react';
import axios from 'axios';

class CommentBox extends Component {

    constructor(props) {
        super(props);
      }

      state = {
        userComments: []
      }

      componentDidMount() {
        const fetchPosts = async () => {
            const res = await axios.get('https://backend-express.herokuapp.com/userComments');
            this.setState({...this.state, userComments: res.data})
          };
          fetchPosts();
        }

          getCommentData = () => {
            const commentContent = document.querySelector(".comment-box-container__div-comment-box").textContent;
            axios.post('https://backend-express.herokuapp.com/userComments', { commentContent })
           }


    render() {

        return(
            <div className="comment-box-container">
             <div className="comment-box-container__div">
             <button className="comment-box-container__post-comment-btn" onClick={this.getCommentData}> Post Comment</button>
             <div className="comment-box-container__div-comment-box" contentEditable="true"></div>
             </div>

             <div className="comment-box-container__show-coments-section">
             {this.state.userComments.map(comment => 
             <section>
            <h3>{comment.date}</h3>
            {comment.title}
            </section>
            )}
             </div>
             </div>
        )
    }
}

export default CommentBox;

和我的 server.js:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3001;
const itemRoutes = express.Router();

app.use(cors());
app.use(bodyParser.json());



mongoose.connect("mongodb://admin:user@password/fghfghfhf", { useNewUrlParser: true } )

const connection = mongoose.connection;

connection.once('open', function() {
  console.log('Connection to MongoDB established succesfully!');
});

// Serve static assets
if(process.env.NODE_ENV === 'production') {
  app.use(express.static('build'));
}


itemRoutes.route('/').get( async (req, res) => {
  let collection = connection.collection("posts");
  let response = await collection.find({})
  .toArray();
  res.send(response);
});

itemRoutes.route('/userComments').get( async (req, res) => {
  let collection = connection.collection("user_comments");
  let response = await collection.find({})
  .toArray();
  res.send(response);
});


app.use('/', itemRoutes);
app.use('/userComments', itemRoutes);



app.listen(PORT, function() {
  console.log('Server is running on' + ' ' + PORT);
})

最佳答案

你应该使用 post 和 express 来获取 post 数据

  app.post('/userComments', function(req, res) {
     //Perform your actions here
     // res.body contains the sent data

   });

关于javascript - 无法在 React 中将数据发布到 mlab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58832317/

相关文章:

javascript - Firebase JS v9 中 Google Auth Provider 的 select_account 提示

node.js - Socket.io 不与 express 共享 session

reactjs - Jest 在 React 中测试异步图像上传

javascript - NodeJS/ExpressJS : proxy an HTTP video stream (from VLC)

javascript - 在 Node.js Express 应用程序中加载特定于 View 的 JavaScript

javascript - 在滚动列表的最后一项和父项的边框之间添加空间

javascript - 在 React useState Hook 中删除数组的第一个元素?

javascript - 用于用户登录/注册的 Django 模式 - 表单渲染问题

javascript - 检查元素继承了哪些属性

javascript - Jest 报道,所有值为零