【发布时间】:2020-03-25 19:57:18
【问题描述】:
我在 Mlab 中有一个数据库,它是 MongoDB,它有两个集合,我正在尝试创建一个 POST 端点,我可以将用户在评论框中输入的任何内容发布到该端点。但是我做错了,因为当我用 Postman 测试我的端点时,它说 404 找不到端点。尝试通过评论框发帖当然是行不通的。这是我的帖子端点的网址:
https://astroecstatic-express.herokuapp.com/comments。但是,如果我在浏览器中运行它,它会显示一个空数组,那么我在尝试 POST 时为什么会出现 404 错误?我做错了什么,如何制作我的 POST 端点?这是我的 node.js 服务器:
// Requiring the dependencies
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();
let Comment = require('./comment.model');
app.use(cors());
app.use(bodyParser.json());
mongoose.connect("mongodb://admin:SomeUSersecretpassword.mlab.com:41968/heroku_hc9xjmcl", { 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('/comments').get( async (req, res) => {
let collection = connection.collection("comments");
let response = await collection.find({})
.toArray();
res.send(response);
});
itemRoutes.route('/comments')
.post((req, res) => {
res.setHeader('Content-Type', 'application/json');
let comment = new Comment(req.body);
comment.save()
.then(comment => {
res.status(200).json({comment})
})
.catch(err => {
res.status(400).send('failed')
})
});
app.use('/', itemRoutes);
app.use('/comments', itemRoutes);
app.listen(PORT, function() {
console.log('Server is running on' + ' ' + PORT);
})
和我的帖子组件:
import React, { Component } from 'react';
import axios from 'axios';
class CommentBox extends Component {
constructor(props) {
super(props);
this.path = window.location.href;
this.postId = this.path.split("/").slice(-1)[0];
}
state = {
userComments: []
}
componentDidMount() {
const fetchPosts = async () => {
const res = await axios.get('https://astroecstatic-express.herokuapp.com/comments');
this.setState({...this.state, userComments: res.data})
};
fetchPosts();
}
getCommentData = (res) => {
let today = new Date();
let dd = String(today.getDate()).padStart(2, '0');
let mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
let yyyy = today.getFullYear();
today = mm + '/' + dd + '/' + yyyy;
const commentContent = document.querySelector(".comment-box-container__div-comment-box").textContent;
axios.post('https://astroecstatic-express.herokuapp.com/comments', {title: commentContent, date: today, commentId: this.postId })
window.location.reload();
}
render() {
let currentPostComments = this.state.userComments.filter((item) => {
return item.commentId === this.postId
})
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">
{currentPostComments.map(comment =>
<section>
<h3>{comment.date}</h3>
{comment.title}
</section>
)}
</div>
</div>
)
}
}
export default CommentBox;
【问题讨论】:
-
您说您发帖的路线是
/comments,但您的代码只显示了/userComments的发帖路线。另外,为两条不同的基本路由配置两次itemRoutes路由器也可能是错误的。 -
@jfriend00
userCommetns是一个错字,我更新了我的问题。在我的原始代码中,端点是 /cmets 但它仍然不起作用。我需要从该端点进行 GET 和 POST,这就是它们被配置两次的原因。
标签: node.js reactjs mongodb express mongoose