簡體   English   中英

Vercel/NextJS:如何在本地開發期間從前端訪問無服務器功能?

[英]Vercel/NextJS: How to access serverless functions from frontend during local development?

我的 React/NextJS 前端有一個 Button 組件,該組件在單擊按鈕時通過無服務器 function 獲取數據。 我想在本地開發期間使用 Vercel 開發/CLI 工具測試此功能。 嘗試訪問我的 lambda 函數時,我得到 404 結果。 以下是我到目前為止所經歷的大致步驟:

  1. 使用開發腳本創建package.json
...
"scripts": {
    "dev": "yarn codegen && next --hostname=0.0.0.0 --port=3001",
}
...
  1. 鏈接到已部署的 vercel 項目
  2. 創建vercel.json以指定構建和路由:
...
    "builds": [
        { "src": "*.html", "use": "@now/static" },
        { "src": "pages/api/*.py", "use": "@now/python" },
    ],
    "routes": [
        { "src": "/api/validate", "dest": "/pages/api/validate.py" }
    ]
...
  1. 創建我的測試 Lambda function(在 python 中):
from http.server import BaseHTTPRequestHandler
from datetime import datetime

class handler(BaseHTTPRequestHandler):

  def do_GET(self):
    self.send_response(200)
    self.send_header('Content-type', 'text/plain')
    self.end_headers()
    self.wfile.write(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')).encode())
    return
  1. 創建我的按鈕組件:
...
    <Button
        variant="contained"
        color="secondary"
        onClick={() => {
            fetch('api/validate')
                .then(response => { console.log(response)
                    response.json() })
                .then(data => console.log(data))
        }}
    >
        Generate sample dataset
    </Button>
...
  1. 運行vercel dev
  2. localhost:3001訪問網站(下一個開發服務器地址)
  3. 點擊按鈕

結果

我收到404響應

注意:我可以從localhost:3000/pages/api/validate.py (vercel 開發服務器地址)訪問 lambda function。 這似乎是手動啟動 lambda function 構建和服務過程。 我認為它應該已經從vercel.json規范中構建和服務,並且可以在localhost:3001/api/validate上找到。 這似乎與Vercel 文檔一致。

注意 2:下一個開發/CLI 工具可以很好地構建和提供 javascript/typescript 文件。 我也在使用 python 和 Go 功能,Vercel dev/CLI 支持但不支持 Next

我的解決方案是使用vercel dev而不是next devyarn dev ,並在.env文件中使用指向 function url 的環境變量。 此 env 變量應以NEXT_PUBLIC_ ,以便在構建過程中由 next.js 注冊並傳遞給process.env

# .env
NEXT_PUBLIC_FUNCTIONS_BASE_URL="http://localhost:3000" # 3000 is vercel port
# component.js
...
fetch(process.env.NEXT_PUBLIC_FUNCTIONS_BASE_URL + '/api/function-name')
...

您需要將端口從vercel dev傳遞到上游 CLI,在本例中為next dev

{
  "scripts": {
    "dev": "yarn codegen && next dev --port=$PORT",
  }
}

現在,當您運行vercel dev時,臨時端口將從開發服務器代理。

如果將/pages/api重命名為/api api ,也可以刪除vercel.json

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM