Module not found 'express' when deploying to azure app service

huangapple go评论88阅读模式
英文:

Module not found 'express' when deploying to azure app service

问题

以下是您提供的内容的翻译:

我有一个名为 server.js 的节点文件我可以在本地成功运行它它的代码如下

const express = require('express')
const compression = require('compression')
const path = require('path')
const { renderPage } = require('vite-plugin-ssr/server')

const isProduction = process.env.NODE_ENV === 'production'
const root = path.resolve(__dirname, '..')
const clientPath = path.join(root, 'client')

async function startServer() {
  const app = express()

  app.use(compression())

  if (isProduction) {
    const sirv = require('sirv')
    app.use(sirv(clientPath))
  } else {
    const vite = require('vite')
    const viteDevMiddleware = (
      await vite.createServer({
        root,
        server: { middlewareMode: true },
      })
    ).middlewares
    app.use(viteDevMiddleware)
  }

  // eslint-disable-next-line consistent-return
  app.get('*', async (req, res, next) => {
    const pageContextInit = {
      urlOriginal: req.originalUrl,
    }
    const pageContext = await renderPage(pageContextInit)
    const { httpResponse } = pageContext
    if (!httpResponse) return next()
    const {
      body, statusCode, contentType, earlyHints,
    } = httpResponse
    if (res.writeEarlyHints) res.writeEarlyHints({ link: earlyHints.map((e) => e.earlyHintLink) })
    res.status(statusCode).type(contentType).send(body)
  })

  const port = process.env.PORT || 5173
  app.listen(port)
  console.log(`Server running at http://localhost:${port}`)
}

startServer()

我还可以在运行 npm run build 后从我的 dist 文件夹中提供服务,没有任何问题。但是,一旦我将其部署到 Azure 的应用服务并尝试在那里运行它,我就会遇到错误。这是我的应用服务启动命令:

pm2 start js/server.js --no-daemon

我的流水线看起来像这样:

name: Azure dev deployment

on:
  push:
    branches:
      - main
env:
  AZURE_WEBAPP_NAME: {name}
  AZURE_WEBAPP_PACKAGE_PATH: './dist'
  NODE_VERSION: '16.x'

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    container: node:16
    steps:
      - uses: actions/checkout@v2
      - name: set script to remove husky in CI
        run: npm set-script prepare ''
      - name: Dependency installation
        run: npm ci
      - name: linter
        run: npm run lint
      - name: build
        env:
          DISABLE_ESLINT_PLUGIN: true
        run: npm run build --if-present
      - name: tests
        env:
          DISABLE_ESLINT_PLUGIN: true
        run: npm test
      - name: 'Deploy to Azure WebApp'
        uses: azure/webapps-deploy@v2
        with:
          app-name: ${{ appName }}
          publish-profile: ${{ publishProfile }}

在我的部署包中是否应包含 node_modules 和/或 package.json?我有点迷失方向,正在猜测为什么会出现此错误,我会感激任何帮助。

谢谢!


<details>
<summary>英文:</summary>
I have a node server.js file which i can run just fine locally, and it looks like this:
const express = require(&#39;express&#39;)
const compression = require(&#39;compression&#39;)
const path = require(&#39;path&#39;)
const { renderPage } = require(&#39;vite-plugin-ssr/server&#39;)
const isProduction = process.env.NODE_ENV === &#39;production&#39;
const root = path.resolve(__dirname, &#39;..&#39;)
const clientPath = path.join(root, &#39;client&#39;)
async function startServer() {
const app = express()
app.use(compression())
if (isProduction) {
const sirv = require(&#39;sirv&#39;)
app.use(sirv(clientPath))
} else {
const vite = require(&#39;vite&#39;)
const viteDevMiddleware = (
await vite.createServer({
root,
server: { middlewareMode: true },
})
).middlewares
app.use(viteDevMiddleware)
}
// eslint-disable-next-line consistent-return
app.get(&#39;*&#39;, async (req, res, next) =&gt; {
const pageContextInit = {
urlOriginal: req.originalUrl,
}
const pageContext = await renderPage(pageContextInit)
const { httpResponse } = pageContext
if (!httpResponse) return next()
const {
body, statusCode, contentType, earlyHints,
} = httpResponse
if (res.writeEarlyHints) res.writeEarlyHints({ link: earlyHints.map((e) =&gt; e.earlyHintLink) })
res.status(statusCode).type(contentType).send(body)
})
const port = process.env.PORT || 5173
app.listen(port)
console.log(`Server running at http://localhost:${port}`)
}
startServer()
I can also serve it from my dist folder after running npm run build without any issues. But as soon as i deploy it to my app service in azure and try to run it there i get the error. Here is my app service startup command:
pm2 start js/server.js --no-daemon
My pipeline looks like this:
name: Azure dev deployment
on:
push:
branches: 
- main
env:
AZURE_WEBAPP_NAME: {name}
AZURE_WEBAPP_PACKAGE_PATH: &#39;./dist&#39;
NODE_VERSION: &#39;16.x&#39;                
jobs:
build-and-deploy:
runs-on: ubuntu-latest
container: node:16
steps:
- uses: actions/checkout@v2
- name: set script to remove husky in CI
run: npm set-script prepare &#39;&#39;
- name: Dependency installation
run: npm ci
- name: linter
run: npm run lint
- name: build
env:
DISABLE_ESLINT_PLUGIN: true
run: npm run build --if-present
- name: tests
env:
DISABLE_ESLINT_PLUGIN: true
run: npm test
- name: &#39;Deploy to Azure WebApp&#39;
uses: azure/webapps-deploy@v2
with: 
app-name: ${{ appName }}
publish-profile: ${{ publishProfile }}
Should node_modules and/or package.json be included in my deployment package to my app service? I&#39;m a bit lost here and trying to speculate as to why I&#39;m getting this error and would appreciate any help.
Thanks
</details>
# 答案1
**得分**: 1
确保在运行 GitHub Action 工作流的 GitHub 仓库的节点模块中包含 express.js:
**我的 GitHub 仓库包含 Express.js 应用程序:**
![在此输入图片描述](https://i.imgur.com/yeGhwJ8.png)
**我的 package.json:**
```json
{
"name": "myexpressapp7",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"ejs": "~2.6.1",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"morgan": "~1.9.1",
"pm2": "^5.3.0"
}
}

节点模块文件夹中包含 express 包:

Module not found 'express' when deploying to azure app service

我的 GitHub 工作流:

name: 构建并部署 Node.js 应用程序到 Azure Web App - valleywebapp984

on:
  push:
    branches:
      - master
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2

      - name: 设置 Node.js 版本
        uses: actions/setup-node@v1
        with:
          node-version: '18.x'

      - name: npm 安装,构建和测试
        run: |
          npm install
          npm run build --if-present
          npm run test --if-present          
      - name: 上传部署作业的构件
        uses: actions/upload-artifact@v2
        with:
          name: node-app
          path: .

  deploy:
    runs-on: ubuntu-latest
    needs: build
    environment:
      name: 'production'
      url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}

    steps:
      - name: 从构建作业下载构件
        uses: actions/download-artifact@v2
        with:
          name: node-app

      - name: '部署到 Azure Web App'
        id: deploy-to-webapp
        uses: azure/webapps-deploy@v2
        with:
          app-name: 'valleywebapp984'
          slot-name: 'production'
          publish-profile: ${{ secrets.AzureAppService_PublishProfile_2eccd9239cc34b3990c26fadf7c6ae60 }}
          package: .

输出:

Module not found 'express' when deploying to azure app service

Module not found 'express' when deploying to azure app service

为了运行 pm2 服务器,请参考我的 Stack Overflow 帖子回答 此处

将此作为 Web 应用程序的启动命令添加到 Web 应用程序中,重新加载您的 Web 应用程序并像下面这样检查日志流:

启动命令:

pm2 start  ./bin/www

Module not found 'express' when deploying to azure app service

英文:

Make sure the express.js is included in the node modules in your github repository where you're running the github action workflow:-

My github repository with Express.js app:-

Module not found 'express' when deploying to azure app service

My package.json:-

{
  &quot;name&quot;: &quot;myexpressapp7&quot;,
  &quot;version&quot;: &quot;0.0.0&quot;,
  &quot;private&quot;: true,
  &quot;scripts&quot;: {
    &quot;start&quot;: &quot;node ./bin/www&quot;
  },
  &quot;dependencies&quot;: {
    &quot;cookie-parser&quot;: &quot;~1.4.4&quot;,
    &quot;debug&quot;: &quot;~2.6.9&quot;,
    &quot;ejs&quot;: &quot;~2.6.1&quot;,
    &quot;express&quot;: &quot;~4.16.1&quot;,
    &quot;http-errors&quot;: &quot;~1.6.3&quot;,
    &quot;morgan&quot;: &quot;~1.9.1&quot;,
    &quot;pm2&quot;: &quot;^5.3.0&quot;
  }
}

node modules folder contains express package:-

Module not found 'express' when deploying to azure app service

My github workflow:-

name: Build and deploy Node.js app to Azure Web App - valleywebapp984

on:
  push:
    branches:
      - master
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2

      - name: Set up Node.js version
        uses: actions/setup-node@v1
        with:
          node-version: &#39;18.x&#39;

      - name: npm install, build, and test
        run: |
          npm install
          npm run build --if-present
          npm run test --if-present          
      - name: Upload artifact for deployment job
        uses: actions/upload-artifact@v2
        with:
          name: node-app
          path: .

  deploy:
    runs-on: ubuntu-latest
    needs: build
    environment:
      name: &#39;production&#39;
      url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}

    steps:
      - name: Download artifact from build job
        uses: actions/download-artifact@v2
        with:
          name: node-app

      - name: &#39;Deploy to Azure Web App&#39;
        id: deploy-to-webapp
        uses: azure/webapps-deploy@v2
        with:
          app-name: &#39;valleywebapp984&#39;
          slot-name: &#39;production&#39;
          publish-profile: ${{ secrets.AzureAppService_PublishProfile_2eccd9239cc34b3990c26fadf7c6ae60 }}
          package: .

Output:-

Module not found 'express' when deploying to azure app service

Module not found 'express' when deploying to azure app service

In order to run the pm2 server, Refer my SO thread answer here

Add this as a start up command in the Web app, reload your web app and check the Log stream like below:-

Start up command:-

pm2 start  ./bin/www

Module not found 'express' when deploying to azure app service

答案2

得分: 0

这是我的终端输出当我运行az webapp log tail时:

英文:

Module not found 'express' when deploying to azure app service

This is what my terminal spits out when I az webapp log tail

huangapple
  • 本文由 发表于 2023年6月28日 23:59:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76574893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定