我的function /NextJS前端有一个Button组件,当单击按钮时,它通过一个无服务器函数获取数据。我想在本地开发期间使用Vercel /CLI工具测试这个功能。当尝试访问lambda函数时,我将得到404的结果。以下是我到目前为止所经历的大致步骤:
package.json:...
"scripts": {
"dev": "yarn codegen && next --hostname=0.0.0.0 --port=3001",
}
...vercel.json以指定生成和路由:...
"builds": [
{ "src": "*.html", "use": "@now/static" },
{ "src": "pages/api/*.py", "use": "@now/python" },
],
"routes": [
{ "src": "/api/validate", "dest": "/pages/api/validate.py" }
]
...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...
<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>
...vercel devlocalhost:3001网站(下一个开发服务器地址)结果
我收到了404的回复
注意:我可以从localhost:3000/pages/api/validate.py (vercel服务器地址)访问lambda函数。这似乎是手动启动lambda函数构建和服务进程。我认为它应该是根据vercel.json规范构建和提供的,并且可以在localhost:3001/api/validate上使用。这似乎符合Vercel文档的观点。
注2: Next dev/CLI工具构建并提供javascript/typescript文件。我也使用python和Go函数,Vercel dev/CLI支持这些函数,但Next不支持。
发布于 2020-07-28 22:30:40
我的解决方案是使用vercel dev而不是next dev或yarn dev,并在指向函数url的.env文件中使用环境变量。这个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')
...https://stackoverflow.com/questions/62569501
复制相似问题