node.js在索引路由上表达404错误

时间:2019-07-08 11:03:17

标签: node.js express

我正在网站上部署我的nodejs项目,问题是当我们在cpanel上设置它时,在尝试访问索引路由时它显示404错误,所有其他路由都可以,并且没有任何问题。我正在使用“ npm start”运行它,端口为3005,当我通过网站ip和端口访问它时,这似乎没有问题,但是当我使用网站域访问它时,索引路由上也会显示404错误本地主机一切正常

app.js

import debug = require('debug');
import express = require('express');
import path = require('path');
import routes from './routes/index';
import test1 from './routes/test1';
import test2 from './routes/test2';
import test3 from './routes/test3';
import helmet = require('helmet');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var FileStore = require('session-file-store')(session);
var device = require('express-device');
var compression = require('compression');
app.use(bodyParser.urlencoded({extended: true})); 
app.use(bodyParser.json());       // to support JSON-encoded bodies
app.use(device.capture({ parseUserAgent: true }));
app.use(express.json());       // to support JSON-encoded bodies
app.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies
app.use(cookieParser());
app.use(compression());
app.use(helmet());
app.set('trust proxy', 1);
app.use(session({
    secret: 'test',
    resave: false,
    store: new FileStore(),
    saveUninitialized: true,
    cookie: {
        secure: false, //for https
        maxAge: 60000
    }
}));
Array.prototype.unique = function () {
    var a = this.concat();
    for (var i = 0; i < a.length; ++i) {
        for (var j = i + 1; j < a.length; ++j) {
            if (a[i].id === a[j].id)
                a.splice(j--, 1);
        }
    }

    return a;
};
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes); // 404 error for this line
app.use('/test1', test1);
app.use('/test2', test2);
app.use('/test3', test3);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err['status'] = 404;
    next(err);
});
app.use((req, res, next) => {
    const oldRedirect = res.redirect;
    res.redirect = function (...args) {
        if (req.session) {
            req.session.save(() => Reflect.apply(oldRedirect, this, args));
        } else {
            Reflect.apply(oldRedirect, this, args);
        }
    }
});
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use((err: any, req, res, next) => {
        res.status(err['status'] || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use((err: any, req, res, next) => {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

app.set('port', process.env.PORT || 3005);

var server = app.listen(app.get('port'), function () {
    debug('Express server listening on port ' + server.address().port);
});

index.js

import express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
    if (req.session.test) {
        return res.redirect('/test1');
    } else if (req.session.test2) {
        return res.redirect('/test2');
    } else {
        return res.redirect('/test3');
    }
});

export default router;

package.json

"scripts": {
    "start": "NODE_ENV=production node app"
  },

htaccess

RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^ http://%{HTTP_HOST}:3005%{REQUEST_URI} [P]

<FilesMatch "\.(png)$">
    <IfModule mod_headers.c>
        Header set Access-Control-Allow-Origin "*"
    </IfModule>
</FilesMatch>
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php70” package as the default “PHP” programming language.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php70 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
找不到

404。我希望索引重定向到test1或test2或test3,但是索引上出现404错误。我可以通过URL访问test1或test2或test 3

我收到的错误代码:

Error: Not Found
    at /mnt/volume-sfo2-04/test/public_html/test/app.js:78:15
    at Layer.handle [as handle_request] (/mnt/volume-sfo2-04/test/public_html/test/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/mnt/volume-sfo2-04/test/public_html/test/node_modules/express/lib/router/index.js:317:13)
    at /mnt/volume-sfo2-04/test/public_html/test/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/mnt/volume-sfo2-04/test/public_html/test/node_modules/express/lib/router/index.js:335:12)
    at next (/mnt/volume-sfo2-04/test/public_html/test/node_modules/express/lib/router/index.js:275:10)
    at /mnt/volume-sfo2-04/test/public_html/test/node_modules/express/lib/router/index.js:635:15
    at next (/mnt/volume-sfo2-04/test/public_html/test/node_modules/express/lib/router/index.js:260:14)
    at Function.handle (/mnt/volume-sfo2-04/test/public_html/test/node_modules/express/lib/router/index.js:174:3)
    at router (/mnt/volume-sfo2-04/test/public_html/test/node_modules/express/lib/router/index.js:47:12)

1 个答案:

答案 0 :(得分:0)

DirectoryIndex似乎有问题,它正在node.js目录中寻找app.use(“ /”)的index.php文件。多亏了这个问题,我的问题才得以解决htaccess-routing-to-node-app