Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

javascript - I have deployed a node app in heroku which is failing to execute posting comments and deleting comments whereas adding a new post works fine

I have recently developed a mern app and every thing worked fine in my local environment but later when i deployed the node server to heroku posting and deleting of comments is not working but i have used the same format of code to add a new post and it works fine even in heroku. Could any find a solution for this? I faced the same problem even after deploying my server to glitch also. This is my node server

require("dotenv").config();
const { Mongoose } = require("mongoose");
const express=require("express");
cors=require("cors");
mongoose=require("mongoose");
const app=express();
app.use(cors());
app.options('*', cors());
app.use(express.json());
mongoose.set('useFindAndModify', false);
mongoose.connect(process.env.DB_URL,{useNewUrlParser:true,useUnifiedTopology:true});
const UserSchema = new mongoose.Schema({
    username: String,
    password: String
  });
  const User = mongoose.model('User', UserSchema);
  const postSchema = new mongoose.Schema({
    title: String,
    user_name : String,
    text: String,
    comments:[ {user_name:String,text:String}]
   
  });
  const Post = mongoose.model('Post', postSchema);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    app.listen(process.env.PORT||4000,function(req,res)
    {
        console.log("server is running");
    });
});
app.post("/register", async function(req,res)
{ 
    const {username,password} = req.body;
    const user=await User.findOne({username}).exec();
    if(user){
        res.status(500),
        res.json({message:"user already registered"});
        return;
    }
    await User.create({username,password});
    res.json({
        message:"success"}
    )
});
app.post("/login", async function(req,res)
{ 
    const {username,password} = req.body;
    const user=await User.findOne({username}).exec();
    if(!user || user.password!==password){
        res.status(500),
        res.json({message:"invalid credentials"});
        return;
    }
    
    res.json({
        message:"success"}
    )
});
app.post("/posts", async function(req,res)
{ 
 const {authorization}=req.headers;
 const [,token]=authorization.split(" ");
 const [username,password]=token.split(":")
 const postsItems=req.body;
 const user=await User.findOne({username}).exec();
 if(!user || user.password!==password){
    res.status(403),
    res.json({message:"invalid credentials"});
    return;
}
//const Items= await Post.findOne().exec();
    await Post.create(
        {
            "user_name":user.username,
            "title":postsItems.title,
            "text":postsItems.text,
            "comments":[]
        }
    )


});
app.get("/posts", async function(req,res)
{ 
 const {authorization}=req.headers;
 const [,token]=authorization.split(" ");
 const [username,password]=token.split(":")
 const todosItems=req.body;
 const user=await User.findOne({username}).exec();
 if(!user || user.password!==password){
    res.status(403),
    res.json({message:"invalid credentials"});
    return;
}
const posts= await Post.find().exec();
return(res.json(posts))
});
app.post("/comment", async function(req,res)
{ 
 const {authorization}=req.headers;
 const [,token]=authorization.split(" ");
 const [username,password]=token.split(":")
 const postsItems=req.body;
 const id=postsItems.post_id
 const user=await User.findOne({username}).exec();
 if(!user || user.password!==password){
    res.status(403),
    res.json({message:"invalid credentials"});
    return;
}
comment={user_name:postsItems.user_name,text:postsItems.text}
 await Post.findOneAndUpdate(
     {_id:id},
     {
     $push:{comments:comment}
    });
    return(res.json({message:"Delete request recieved"}))
});
app.post("/post/", async function(req,res)
{ 
 const {authorization}=req.headers;
 const [,token]=authorization.split(" ");
 const [username,password]=token.split(":")
 const postsItems=req.body;
 const user=await User.findOne({username}).exec();
if(!user || user.password!==password){
    res.status(403),
    res.json({message:"invalid credentials"});
    return;
}
const post= await Post.findOne({_id:postsItems.id}).exec();
return(res.json(post))
});
app.delete("/comment", async function(req,res)
{ 
 const {authorization}=req.headers;
 const [,token]=authorization.split(" ");
 const [username,password]=token.split(":")
 const postsItems=req.body;
 const user=await User.findOne({username}).exec();
 if(!user || user.password!==password){
    res.status(403),
    res.json({message:"invalid credentials"});
    return;
}
post_id=postsItems.post_id
comm_id=postsItems.comm_id
await Post.findOneAndUpdate(
    {_id:post_id},
    {
    $pull:{'comments':{_id:comm_id}}
   });
  return(res.json({message:"Delete request recieved"}))
});

These are frontend react methods that are responsible for deleting and adding comments

import React, {   useEffect, useState } from "react";
import DeleteIcon from "@material-ui/icons/Delete"
import { Link} from "react-router-dom";
const url="https://postit--server.herokuapp.com"
export default function Ind(props)
{
    const [credentials,setCredentials]=useState(null)
   function credGetter()
    {
      const x=JSON.parse(localStorage.getItem("creds"));
       setCredentials(x);
    }
    if(credentials==null)
    {
    window.onload=credGetter();
  }
  const [comments,setComments] =useState([]);
  const [comText,setcomText] = useState("");
  const [Data,setData] =useState("");
    useEffect(()=>{
        fetch(url+"/post/",{
            method: "POST",
            headers: {"Content-Type":"application/json",
            Authorization:`Basic ${credentials.username}:${credentials.password}`
        },
        body:JSON.stringify({id:props.match.params.id})
        }).then((response)=>response.json()).then((Data)=>setData(Data))
     },[credentials,props.match.params.id])
     const Add=(e)=>{
        e.preventDefault();
        if(!comText) return;
       const newComment={user_name:credentials.username,text:comText,post_id:props.match.params.id}
        const newComments=[...comments,newComment]
        setComments(newComments)
        setcomText("");
        console.log(newComment)
        persist(newComment)
      }
   
      const persist=(newComment)=>
      {
          fetch(url+"/comment",{
              method:"POST",
              headers: {"Content-Type":"application/json",
              Authorization:`Basic ${credentials.username}:${credentials.password}`
          },
              body: JSON.stringify(newComment)
          })
          window.location.reload("/",true)
      }  
      const Delete=(e)=>{
        fetch(url+"/comment",{
            method:"DELETE",
            headers: {"Content-Type":"application/json",
            Authorization:`Basic ${credentials.username}:${credentials.password}`
        },
        body:JSON.stringify({post_id:props.match.params.id,comm_id:e})
        })
        window.location.reload("/post/"+e,true)
    }
   return(
    <div  className="container">
        {credentials &&<Link to="/" id="q">Home</Link>}
        <div key={Data._id} className="post">
        <h1>{Data.title}</h1>
        <p>{Data.text}</p>
        </div>
  <form onSubmit={Add}>
  <div className="form-inline container">
    <label style={{color: "black",fontSize:"20px"}}>Add your comment :</label>
    <textarea className="form-control" rows="2" id="combox" onChange={(e)=>setcomText(e.target.value)}></textarea>
    <br/>
    <button type="submit" className="btn btn-outline-primary logout">Comment</button>
  </div>
</form>
<div className="comment">
    {Data.comments ?  Data.comments.map((comment)=>(
        <div key={comment._id}>
            <h6>Commented By : {comment.user_name}</h6>
            <p>{comment.text}</p>
          {comment.user_name===credentials.username && <DeleteIcon fontSize="small" style={{color:"#fcab05"}} onClick={()=>Delete(comment._id)}/>}
            <hr/>
        </div>
    ))      :<p>No comments</p>    }
 </div>
    </div>
   )
}

These are heroku logs:

2021-01-26T07:08:58.438990+00:00 heroku[router]: at=info method=OPTIONS path="/comment" host=postit--server.herokuapp.com request_id=e9585586-c582-4c7f-a541-1bcc51caf0e0 fwd="160.238.73.97" dyno=web.1 connect=1ms service=2ms status=204 bytes=315 protocol=https

POST method and DELETE method are not getting invoked after options and status is 204 after options

question from:https://stackoverflow.com/questions/65897336/i-have-deployed-a-node-app-in-heroku-which-is-failing-to-execute-posting-comment

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...