【问题标题】:POST endpoint created with Node.js not found找不到使用 Node.js 创建的 POST 端点
【发布时间】: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


【解决方案1】:

这是在路由器上为/comments 创建.get().post() 路由的简单方法:

 itemRoutes.get("/comments", function(req, res, next) {
      // code here
 });

 itemRoutes.post("/comments", function(req, res, next) {
      // code here
 });

 app.use(itemRoutes);

您也可以像这样使用.route()

 itemRoutes.route("/comments").get(function(req, res, next) {
      // code here
 }).post(function(req, res, next) {
      // code here
 });

 app.use(itemRoutes);

而且,您甚至没有为这两条路由使用路由器的令人信服的理由。你也可以这样做:

 app.get("/comments", ...);
 app.post("/comments", ...);

或者

 app.route("/comments")
    .get(...)
    .post(...);

而且,甚至连路由器都不能用于两条顶级路由。

【讨论】:

  • 没有。你的app.use() 看起来不是这样,而且你没有像我展示的那样使用.route()
  • 这不是我一直在做的吗?:``` itemRoutes.route('/cmets').get( async (req, res) => { let collection = connection.collection( "cmets"); 让 response = await collection.find({}) .toArray(); res.send(response); }); itemRoutes.route('/cmets') .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') }) }); ```
  • 仅供参考,.route() 的唯一用途是将多条路由链接在同一条路径上。如果您不打算在一个 itemRoutes.route() 语句上链接多个路由,那么使用 .route() 根本没有意义,您不妨使用我上面展示的第一种方法。
  • @MahmaDeva - 另外,请注意,这种情况根本不适用于路由器,因为这些都是在已知 app 的地方定义的所有顶级路由。你也可以只做app.get()app.post(),根本不用路由器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-10
  • 2021-12-11
  • 1970-01-01
  • 2018-01-05
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多