【问题标题】:Deploy an Express server that uses express.static to serve a build folder to Vercel部署一个使用 express.static 为 Vercel 提供构建文件夹的 Express 服务器
【发布时间】:2022-07-16 04:09:13
【问题描述】:

我已经实现了一个 express 服务器,它使用 express.static 为从静态 docusaurus 站点创建的构建文件夹提供服务,以便应用基本身份验证来访问该站点。这在本地运行良好,但在部署到 Vercel 时遇到了麻烦。

目前我的配置是允许在 vercel 上部署的版本呈现基本的身份验证登录页面,但在成功登录后,我被定向到一个页面,状态为:“无法获取 /”

我相信这可能是我的 vercel.json 配置或我的 vercel 模板设置的问题。

我的代码如下:

index.mjs

import express from 'express';
import dotenv from 'dotenv';

dotenv.config();

const app = express();

app.use(express.json());

const authorize = ((req, res, next) => {

    const auth = {login: process.env.USERNAME, password: process.env.PASSWORD}

  
    const b64auth = (req.headers.authorization || '').split(' ')[1] || ''
    const [login, password] = Buffer.from(b64auth, 'base64').toString().split(':')
  
    
    if (login && password && login === auth.login && password === auth.password) {
     
      return next()
    }
  
    res.set('WWW-Authenticate', 'Basic realm="401"') 
    res.status(401).send('Authentication required.') 
});

app.use('/', authorize);
app.use('/', express.static('build'));

app.listen(3000);
console.log(`???? Server ready at http://localhost:3000`);

vercel.json

{
  "version": 2,
  "builds": [{
    "src": "./index.mjs",
    "use": "@vercel/node"
  }],
  "routes": [{"handle": "filesystem"},
    {
      "src": "/.*",
      "dest": "/"
    }
  ]
  

}

package.json - 启动脚本

"start": "node --experimental-modules index.mjs",

我的vercel模板设置为other,启动脚本设置为npm start。

任何想法将不胜感激!

【问题讨论】:

    标签: node.js express basic-authentication vercel docusaurus


    【解决方案1】:

    我遇到了类似的问题:提供一些静态内容并使用 /api 路由。在本地开发中一切正常,但在 vercel 中抛出“Cannot GET/”。

    我的解决方案。

    • 分别构建无服务器和静态内容。
    • /api 调用和静态内容的路由调整。

    我最后的vercel.json

    {
        "version": 2,
        "builds": [
            {
                "src": "server.js",
                "use": "@vercel/node"
            },
            {
                "src": "public/**",
                "use": "@vercel/static"
            }
        ],
        "routes":[
            {
                "src": "/api/(.*)",
                "dest": "server.js"
            },
            {
                "src": "/",
                "dest": "public/index.html"
            },
            {
                "src": "/(.+)",
                "dest": "public/$1"
            }
        ]
    }
    

    注意事项

    1. 所有静态内容都在 /public(html、css、img、js 等)下
    2. server.js 是主要的应用程序:express 和 route 定义。和你的类似。
    3. vercel 构建日志显示:
    Generated build outputs:    
    12:28:55.974     - Static files: 12
    12:28:55.974     - Serverless Functions: 1
    12:28:55.975     - Edge Functions: 0
    ...
    12:28:58.142    Done with "server.js"
    

    也许从这一点您可以找到适合您的情况的解决方案。

    【讨论】:

      猜你喜欢
      • 2017-08-31
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 2016-08-07
      • 1970-01-01
      相关资源
      最近更新 更多