POST路由的React Express Heroku 503错误

时间:2019-02-05 23:02:01

标签: mysql reactjs express heroku cleardb

我的应用程序在本地运行良好。当我部署到Heroku时,发布路线会出现503错误。 GET路由似乎工作正常,因为其中之一是使用Google OAuth登录所需的路由。注销路由也是GET路由,它也可以正常工作。如果有人能告诉我我在做什么错,我将不胜感激。这是我的服务器代码:

let express = require("express");
let cors= require("cors");
let mysql = require("mysql");
const util = require("util");
const keys = require("./config/keys");
const passport = require("passport");
const passportSetup = require("./config/passport-setup");
const bodyParser = require("body-parser");
const flash= require("connect-flash");
const path= require("path");



const cookieSession = require("cookie-session");



let app = express();
app.use(bodyParser.json());
app.use(express.static(__dirname));


app.use(cookieSession({
    //below equals 2 hours 
    maxAge:120*60 * 1000,
    // maxAge:5000,
    keys:[keys.session.cookieKey],
    httpOnly:false  
}));



app.use(passport.initialize());
app.use(passport.session());

if (process.env.NODE_ENV === 'production') {
    console.log("inside prod");
    app.use(express.static(path.join(__dirname,'client/build')));

} 

console.log("1");


let connection = keys.connection;



//this prevents the database connection from closing
//by querying this meaningless query every five seconds
setInterval(()=>{
    connection.query("SELECT 1");
}, 5000);

console.log("connection");
console.log(connection)

app.get("/google", passport.authenticate("google",{

    scope:['profile'],
    failureFlash:"failure"

}),(req,res)=>{
    // console.log(req.flash());
    console.log("/google route");
});





//callback route for google to redirect to
app.get("/auth/google/redirect", passport.authenticate("google"), (req,res)=>{
    console.log("isinde redirect");
    console.log(req.user)

    res.redirect("myurl.com?token="+req.user.token);


});

app.get("/logoutExp",(req,res)=>{

    console.log("logout");
    req.session=null;
    req.logout();
    res.redirect("/");
        })

app.post("/addExercise", (request, res)=>{
    console.log(request.body);

    let workoutId = request.body.exObj.workoutId; //this comes from the request body;
    let numberOfSets = request.body.exObj.numSets;
    let maxReps = request.body.exObj.maxReps;
    let exerciseName = request.body.exObj.exerciseName;
    let weight = request.body.exObj.weight

    addExercise(connection, workoutId, exerciseName, weight).then(results=>{

    let exerciseId = results.insertId;


    // response.send(exerciseId);
        return addSets(connection, exerciseId, numberOfSets, maxReps)
    }).then(response=>{

        return getWorkout(connection, workoutId)
    }).then(response=>{
        res.send(response);
    }).catch(err=>{
        console.log(err);
    })


})


app.post("/retrieveHistory", (req,res)=>{
    console.log(req.session);

        if(req.session.passport.user.token === req.body.token){
        let userId = req.session.passport.user.userId;

        console.log(userId);

        workoutHistory(connection, userId).then(response=>{

            let arr=[];

            for(let i=0; i<response.length; i++){
                arr[i]=response[i].workoutId;

            }

            // console.log(arr);
            if(response.length ===0){
                res.send("0");
            }

            // console.log("inside workouthistory then");
            // console.log(arr);

            return getExercisesInWorkout(connection, arr).then(response=>{
                // console.log("inside wh geiw");
                // console.log(response);
                return getWorkout(connection, arr).then(response=>{

                    // console.log("sldkfjhasldj")
                    res.send(response);

                })

            })

        }).catch(err=>{

            console.log(err);

        })

    } else {

        res.send("not logged in anymore");

    }


})


//this route  retrieves the ongoing incomplete workout if one exists 
app.post("/retrieveCurrent",  (req, res)=>{
    let globalRes = res;

        if(req.session.passport.user.token === req.body.token ){
            let userId = req.session.passport.user.userId;
            // console.log(userId);


            //checking to see if any incomplete workouts exist, if one does, it will be retrieved.
            //if not, one will be created
            checkForIncompleteWorkout(connection, userId).then(response=>{
                // console.log("inside checkForIncompleteWorkout")
                // console.log(response.length);
                if(response.length < 1){


                    res.send(response); 

                } else{

                        let workoutId = response[0].workoutId;

                        getWorkout(connection, workoutId).then(response=>{
                            // console.log("inside else gw");
                            // console.log(response);
                            res.send(response[0]);
                        }).catch(err=>{
                            console.log(err)
                        });     



                }

            }).catch(err=>{console.log(err)})

        } else {



        }

    // res.send(req.session.user);

})

app.post("/makeNewWorkout", (req,res)=>{

    if(req.session.passport.user.token === req.body.token ){

        let userId = req.session.passport.user.userId;

        //creating new workout
        makeNewWorkout(connection,userId).then(response=>{
            // console.log("inside mnw");
            // console.log(response);
                    //retrieving new workout to send back to client
            return getWorkout(connection, response.insertId)
                    }).then(response=>{
                        res.send(response[0])
                    })

    }


})

app.post("/completeWorkout", (req,res)=>{

    if(req.session.passport.user.token === req.body.token ){

        let workoutId = req.body.workoutId;
        // console.log(workoutId);
        completeWorkout(connection, workoutId).then(response=>{
            res.send(response);
        }).catch(err=>{
            res.send(err);
        })

    }

})


 app.post("/addRep", (req,res)=>{

    if(req.session.passport.user.token === req.body.token ){
        let setId = req.body.setId;
        let workoutId = req.body.workoutId;
        // console.log(workoutId);
        addRep(connection, setId).then(response=>{



                return getWorkout(connection, workoutId).then(response=>{
                    res.send(response);
                });


                // return getExercisesInWorkout(connection, )
            }).catch(error=>{

                res.send(error);

            })

    }

})

app.post("/notesHandler", (req,res)=>{

    if(req.session.passport.user.token === req.body.token ){

        let workoutId = req.body.workoutId;
        let notes = req.body.notes;
        notesHandler(connection, workoutId, notes).then(response=>{

            return getWorkout(connection, workoutId).then(response=>{

                res.send(response);

            })

        }).catch(err=>{

            res.send(err);

        })

    }

})

// if (process.env.NODE_ENV === 'production') {
//  app.use(express.static(path.join(__dirname, 'client','build')));
// }



function getIdOfMostRecentWorkout(connection, userId){

    return new Promise((resolve,reject)=>{

        connection.query("SELECT workoutId FROM workouts WHERE userId =? ORDER BY workoutDate DESC LIMIT 1", userId,(error,results)=>{

            if(error)reject(error);

            resolve(results);
        })


    })


}

function checkIfWorkoutExists(connection, workoutId){

    return new Promise((resolve,reject)=>{

        connection.query("SELECT COUNT(*) AS exist FROM workouts WHERE workoutId = ?",workoutId,(error,results)=>{

            if(error) reject(error);

            resolve(results);

        })

    })

}



const port = process.env.PORT || 4000;
let http = require("http");
let server = http.createServer(app,(req,res)=>{
    res.writeHead(200, {"Access-Control-Allow-Origiin": "*"})
});

app.get("/service-worker.js", (req, res) => {
    console.log("service workerssssss");
  res.sendFile(path.join(__dirname + "app/client","build", "service-worker.js"));
});

app.get('/*', (req, res) => {


    console.log("catchallll");
    console.log(req.hostname);
    console.log(req.path);
    console.log(path.join(__dirname + '/client', 'build', 'index.html'));
  res.sendFile(path.join(__dirname + '/client', 'build', 'index.html'));


})

server.listen(port, ()=>{
    console.log("Listening on "+ port)
});

这是日志中的一些内容。以下是其中一种POST路由的错误(所有POST路由均给出相同的错误):

2019-02-05T23:22:46.076348+00:00 heroku[router]: at=error code=H12 
desc="Request timeout" method=POST path="/retrieveCurrent" host=*myurl* request_id=bbcd3e11-2e99-4321-b519-1635a282edcb 
fwd="107.223.198.1" dyno=web.1 connect=1ms service=30001ms status=503 bytes=0 
protocol=https

以下是其中一个GET路由的日志(所有GET路由都给出相同的消息):

2019-02-05T23:22:46.273636+00:00 heroku[router]: at=info method=GET 
path="/logoutExp" host=*myurl* request_id=9833444b-e6a1-4771-a325-5be0d3788c2c 
fwd="107.223.198.1" dyno=web.1 connect=1ms service=3ms status=302 bytes=381 
protocol=https  

1 个答案:

答案 0 :(得分:0)

问题出在我的数据库上。我在本地添加了一些列,而没有更新heroku服务器上数据库中的表。这就是为什么它超时。谢谢。