我正在尝试使用 grunt-express 设置 Grunt 来启动我的 Express 服务器。 读完docs后和 this SO question ,我还是想不通。我已经为我的 Grunt 文件尝试了几种组合。 尽管如此,每次我收到服务器应该提供一个名为“listen”的函数,充当 http.Server.listen 错误
这是我的代码:
Gruntfile.js
module.exports = function (grunt) {
'use strict';
var path = require('path');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
app: {
basePath: 'public',
[...],
serverPath: 'backend'
},
express: {
all: {
options: {
port: 3000,
hostname: '*', //()=>Localhost
bases: '<%= app.basePath %>',
server: '<%= app.serverPath %>/Server.js',
livereload: true
}
}
}
});
grunt.registerTask('server', [
'express',
'open',
'watch'
]);
};
项目结构:
App_Root/
-Backend/
--Server.js
--BackofficeRouter.js
-Public/
--index.html
服务器.js:
var express = require('express');
var backofficeRouter = require('./backofficeRouter.js');
var constants = require('./../public/constants/ConstantsModule.js');
var app = express();
var appRoot = require('app-root-path');
app.use('/backoffice', backofficeRouter);
app.use(express.static(appRoot + '/public'));
app.listen(process.env.PORT || 3000);
BackofficeRouter.js:
backofficeRouter.get('/', function(req, res) {
res.sendFile(path.join(appRoot + '/public/index.html'));
});
我真的不明白 grunt-express 如何与我的 Server.js 文件交互。 我尝试在我的 Gruntfile 中设置默认的 grunt-express 配置,认为它会考虑到我在 Server.js 中的配置。但看起来 grunt-express 的配置会覆盖一切。 关于我可能在哪里犯了错误的任何提示吗?
感谢您的帮助。
最佳答案
服务器应该提供一个名为“listen”的函数,充当 http.Server.listen 错误表明 grunt 任务需要一个包含“listen”方法的服务器实例,因此您应该从您的服务器中删除此行
app.listen(process.env.PORT || 3000);
并将其替换为
module.exports = app;
这样,grunt 任务将收到一个已配置的express 实例,其中包含它正在查找的listen 方法。
关于javascript - Grunt-express 和静态路由 : Server should provide a function called "listen" that acts as http. Server.listen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36621366/