我有一个内容可编辑的简单 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/