【问题标题】:Run NestJS application using app.js (express)使用 app.js (express) 运行 NestJS 应用程序
【发布时间】:2021-09-13 22:57:47
【问题描述】:

我有一个可以正常启动的 NestJS 应用程序:

npm start (npm run start:prod) 要么 节点分布/主节点

但是,我想使用 app.js,但不知道如何配置 app.js 文件来完成此操作。

app.js 文件

var serverType = 'AM-API-MDD';
var express = require('express');
var http = require('http');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 3030;

app.use(function(req,res,next){
    res.header("Access-Control-Allow-Origin","*");
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-client-key, x-client-token, x-client-secret, Authorization");
    next();
    });


app.use(express.static(__dirname + '/dist/'));

//body parse
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ limit: '50mb',extended: true }))

// parse application/json
app.use(bodyParser.json({limit: '50mb', extended: true}))
app.all('/*', function(req, res, next) {
    res.sendFile('dist/main.js', { root: __dirname });
});

// Handle 404
app.use(function(req, res) {
    //res.send(‘404: Page not Found’, 404);
    res.status(404).send({status:404, message: '404 Not Found', type:'client'}); 
   });

// Handle 500
app.use(function(error, req, res, next) {
    res.status(500).send({status:500, message: 'internal error', type:'internal'}); 
   });

//listen
var httpServer = http.createServer(app);
httpServer.listen(port,() => console.log(serverType +' server running on port: '+ port));

【问题讨论】:

  • 我不确定我是否理解这个问题。你想使用这个app.js 文件怎么样?这在我看来就像一个普通的 Express 应用程序,你需要在 Nest 中使用它吗?
  • 我希望能够运行“node app.js”并启动应用程序。 - node-windows 创建一个自动启动应用程序的 Windows 服务。
  • 那么为什么不在项目根tat 导入dist/main 中创建一个app.js 脚本呢?确保首先编译项目,你应该一切顺利。否则 Nest 的 CLI 有一个 start --watch 模式,可以通过 npm 脚本 start:dev 运行,它会在文件更改时自动重新编译并重新启动服务器
  • 如果您对如何使 app.js 执行此操作有任何建议,好吗?我愿意接受建议。 - 如果您从命令行运行,Nest 的“start --watch”很好,但我希望它能够从自动化进程运行,当/如果 Windows 重新启动?我不想打开提示并运行脚本。 node-windows 将创建一个自动运行“node app.js”(或“node server.js”)的服务所以,我想最终,我需要编写节点可以调用的脚本文件,该文件运行“npm start”

标签: node.js express npm nestjs


【解决方案1】:

试图获取 app.js 是错误的方法。

node dist/main.js 运行应用程序 - 所以启动脚本是 main.js 文件。

node-windows 可以引用 main.js 文件,而不是 app.js 文件。

感谢 Jay McDoniel 将我推向正确的方向。

【讨论】:

    猜你喜欢
    • 2022-06-18
    • 1970-01-01
    • 2020-03-07
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 2022-08-23
    相关资源
    最近更新 更多