Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
找不到使用Node.js创建的POST端点_Node.js_Reactjs_Mongodb_Express_Mongoose - Fatal编程技术网

找不到使用Node.js创建的POST端点

找不到使用Node.js创建的POST端点,node.js,reactjs,mongodb,express,mongoose,Node.js,Reactjs,Mongodb,Express,Mongoose,我在Mlab中有一个数据库,它是MongoDB,有两个集合,我正在尝试创建一个POST端点,我可以将用户在commentbox中输入的任何内容发布到该端点。但是我做错了,因为当我用Postman测试我的端点时,它说404找不到端点。当然,试图通过评论框发表评论也不起作用。这是指向我的帖子端点的url: https://astroecstatic-express.herokuapp.com/comments。但是,如果我在浏览器中运行它,它会显示一个空数组,那么当我尝试发布时,为什么会出现404错

我在Mlab中有一个数据库,它是MongoDB,有两个集合,我正在尝试创建一个POST端点,我可以将用户在commentbox中输入的任何内容发布到该端点。但是我做错了,因为当我用Postman测试我的端点时,它说404找不到端点。当然,试图通过评论框发表评论也不起作用。这是指向我的帖子端点的url:
https://astroecstatic-express.herokuapp.com/comments
。但是,如果我在浏览器中运行它,它会显示一个空数组,那么当我尝试发布时,为什么会出现404错误?我做错了什么?我怎样才能使我的文章结束?这是我的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;
import React,{Component}来自'React';
从“axios”导入axios;
类CommentBox扩展组件{
建造师(道具){
超级(道具);
this.path=window.location.href;
this.postId=this.path.split(“/”).slice(-1)[0];
}
状态={
用户评论:[]
}
componentDidMount(){
const fetchPosts=async()=>{
const res=等待axios.get('https://astroecstatic-express.herokuapp.com/comments');
this.setState({…this.state,userComments:res.data})
};
fetchPosts();
}
getCommentData=(res)=>{
让今天=新日期();
让dd=String(today.getDate()).padStart(2,'0');
让mm=String(today.getMonth()+1).padStart(2,'0');//一月是0!
让yyy=today.getFullYear();
今天=mm+'/'+dd+'/'+yyyy;
const commentContent=document.querySelector(“.comment-box-container\uu div-comment-box”).textContent;
轴心柱https://astroecstatic-express.herokuapp.com/comments“,{标题:commentContent,日期:today,commentId:this.postId})
window.location.reload();
}
render(){
让currentPostComments=this.state.userComments.filter((项)=>{
return item.commentId==this.posted
})
返回(
发表评论
{currentPostComments.map(注释=>
{comment.date}
{comment.title}
)}
)
}
}
导出默认注释框;

这里有一种简单的方法,可以在路由器上为
/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", ...);


而且,甚至不要将路由器仅用于两个顶级路由。

您说您要发布到的路由是
/comments
,但您的代码仅显示
/userComments
的发布路由。另外,为两个不同的基本路由配置两次
itemrouts
路由器也可能是错误的。@jfriend00
userCommetns
是一个打字错误,我更新了我的问题。在我的原始代码中,端点是/comments,但它仍然不起作用。我需要从该端点获取和发布,这就是它们被配置两次的原因。否。你的
app.use()
看起来不是这样,你也没有像我所说的那样使用
.route()
。这不是我一直在做的吗?:``itemRoutes.route('/comments').get(async(req,res)=>{let collection=connection.collection(“comments”);let response=wait 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')})```仅供参考,
.route()
的唯一使用点是在同一路径上将多条路线链接在一起。如果您不打算在一个
itemRoutes.route()
语句上链接多个路由,那么使用
.route()
就毫无意义,您也可以使用我上面介绍的第一种方法。@MahmaDeva-还有,请注意,这种情况根本不适用于路由器,因为这些都是在已知
app
的地方定义的顶级路由。你也可以在没有路由器的情况下执行
app.get()
app.post()
 app.route("/comments")
    .get(...)
    .post(...);