【发布时间】:2020-03-08 23:13:45
【问题描述】:
我有一个内容可编辑的简单 div,我可以通过 onclick 事件获取用户在该 div 中键入的任何内容。我想将该数据发送到我在 Mlab 中的数据库,我在 Heroku 上托管我的应用程序。目前,当我尝试发布数据时,我收到 404 错误,几秒钟后我收到GET http://localhost:3000/static/js/0.chunk.js net::ERR_CONNECTION_REFUSED,我不知道为什么,因为我能够通过获取请求检索已经存在的数据。我在这里做错了什么,如何成功发出该帖子请求?这是我的组件:
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);
})
【问题讨论】:
-
为什么在你的服务器中使用
/userComments.get()而你正在从 axios 发送 post 请求? -
因为我还需要支付他们的费用
-
好的。然后首先你在 api 中没有匹配的 post 请求。其次,您需要更改
app.post('/userComments').post((req,res)=>{})。第三,将数据提交到数据库后,您可以再次触发get()api请求,以便您也可以取回数据。
标签: javascript node.js reactjs mongodb express