上传到Heroku后,Node js站点不会响应GET

时间:2015-10-04 19:14:08

标签: javascript node.js heroku

完成我的测试网站并确保它在本地服务器上工作后,我将其上传到Heroku,似乎它没有响应来自网站的任何GET请求,我收到此错误:

  

服务器响应状态为403(禁止)。

它甚至无法加载图片。

我认为问题出在我在server.js中配置应用程序的方式上。 该网站以这种方式构建:

-> public
  -> images
-> views
  main.html
-> server.js

我的server.js代码是:

// Requirements
var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var url = require('url');

var app = express();

// DB Requirements
var mongojs = require('mongojs');
var db = mongojs('mongodb://mysuername:password22@ds0000.mongolab.com:0000/name', ['usersData']);

//Starts listening for incoming connections
var server = app.listen(process.env.PORT || 80 , function (){
    var host = server.address().address;
    var port = server.address().port;
});

// Get the correct db for the users.
var usersData = db.collection('usersData');


Object.defineProperty(Object.prototype, "extend", {
    enumerable: false,
    value: function(from) {
        var props = Object.getOwnPropertyNames(from);
        var dest = this;
        props.forEach(function(name) {
                var destination = Object.getOwnPropertyDescriptor(from, name);
                Object.defineProperty(dest, name, destination);
        });
        return this;
    }
});

// set up standard headers
function setCORS(res) {
    res.setHeader("Access-Control-Allow-Origin", '');
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.set({
        'Content-Type': 'application/json'
    });
}

// Set the session information.
app.use(express.static(__dirname + '/views'));
app.use(cookieParser());
app.use(session({
    secret: '1O2W',
    resave: true,
    saveUninitialized: true
}));
app.engine('html', require('ejs').renderFile);


// Main getter.
app.get('/', function (req, res) {
    res.render("main.html");
});

// Help page getter.
app.get("/help.html", function (req, res) {
    res.render("help.html");
});

// Partners page getter.
app.get("/partners.html", function (req, res) {
    res.render("partners.html");
});

// returns EVERYTHING the client needs when starting up with the user.
app.get('/me', function (req, res) {
    console.log("me request");
    setCORS(res);

    if (!req.session.user) {
        console.log("Error: user not logged in");
        res.send(403, { error: 'Need to login' });
        return;
    }
    console.log("req.session.user: " + req.session.user);

    // get the user
    db.usersData.findOne({ username: req.session.user }, function (err, user) {
        if (err || !user) console.log("db empty, nothing to cleanup");
        else {
            res.send(user);
        }
    });
});

// login with username and password
app.get('/login', function (req, res) {
    setCORS(res);
    var url_parts = url.parse(req.url, true);
    var query = url_parts.query;

    console.log(query);
    if (!query.user || !query.password) {
        res.send(500, { error: "request didn't contain username or password" });
        return;
    }
    // find the user
    db.usersData.findOne({ username: query.user }, function (err, user) {
        if (err || !user) {
            console.log("user " + query.user + " not found");
            res.send(403, { error: "bad username or password" });
            return;
        }
        // verify password
        if (user.password != query.password) {
            console.log("user " + query.username + " bad password - " + user.password + " != " + query.password);
            res.send(403, { error: "bad username or password :(" });
            return;
        }
        console.log("Loging in user: " + user.username + " password: " + query.password);
        req.session.user = user.username;

        res.send({ success: null });
    });
});

// Register a new user (save to the DB)
app.get('/signup', function(req, res){
    setCORS(res);
    var url_parts = url.parse(req.url, true);
    var query = url_parts.query;

    console.log(query);

    // Check that the user name is nt used.
    if (query.user) {
        db.usersData.findOne({username: query.user}, function (err, user) {
            console.log("trying to sign up user:" +  query.user);
            if (user) {
                console.log("Error: user already exists");
                res.send(403, {error: "User already exists."});
                return;
            } else if (err) {
                res.send({error: "mongoDB error"});
                return;
            } else {
                if (db.usersData.findOne(function(err, count) {
                    if (!query.user || !query.password) {
                        console.log("didn't receive user/password on signup");
                        res.send ({error : "no user or password"});
                        return;
                    } else {
                        // Create a new user with empty information.
                        var new_user = {
                            username: query.user,
                            password: query.password,
                            current: [],
                            history: [],
                            friends: [] };
                        db.usersData.save(new_user, function(err, saved) {
                            if( err || !saved ) {
                                console.log("User not saved");
                                res.send ({error : "can not write user to db"});
                                return;
                            }
                            else {
                                console.log("User saved");
                                console.log("Loging in user: " + new_user.username + "password: " + query.password);
                                req.session.user = new_user.username;
                                res.send ({success : "added user to db"});
                            }
                        }); 
                       }
                 }));
               }}); 
}});
);

编辑:我的package.json是:

{
  "name": "w",
  "version": "0.1.0",
  "author": "AV",
  "description": "Site",
  "contributors": [
    "V",
    "A"
  ],
  "main": "./server.js",
  "keywords": [
    "w"
  ],
  "noAnalyze": true,
  "license": "Apache",
  "engines": {
    "node": ">=0.6.14"
  },
  "dependencies": {
    "ejs": "^2.3.1",
    "body-parser": "^1.14.0",
    "express": "~4.0.0",
    "mongojs": "1.2.1",
    "cookie-parser": "1.4.0",
    "express-session": "1.11.3"
  },
  "scripts": {
    "start": "node server.js"
  },
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "git@heroku.com:w.git"
  }
}

谢谢!

1 个答案:

答案 0 :(得分:0)

确保您拥有:

  • 使用save_to_file(@entry)创建的package.json,然后根据需要安装了所有依赖项。
  • npm init上指定版本的节点:

    package.json
  • 在您的软件包上指定的启动脚本,为"engines": { "node": "0.10.x" },

另请确保您可以使用scripts.start启动应用。

详细了解如何将节点部署到Heroku here