为什么这个函数在 NextJS 中可以在本地运行,但部署在 AWS Lambda 中却不行?

Why does this function in NextJS works locally, but not when deployed in AWS Lambda?

我对此做了很多测试和研究,但我就是想不通。我有一个函数在本地 运行 时工作得很好(没有错误),但在部署为 AWS lambda 时失败。

我创建了一个重新创建它的简单示例:

URL 本地http://localhost:3000/flagTest/visible(效果很好 ✅)

URL 部署为 LAMBDAhttps://www.publicfaq.com/flagTest/visible(切换按钮不起作用 ❌)

FILE: /pages/flagTest/[tid].js(在准系统 NextJS 安装上)

import React from 'react'


class FlagTest extends React.Component {
  static async getInitialProps({ query }) {

    return { visible: query.tid }

  }

  constructor(){
    super();

    this.state = {
      showFlag:false,
    }

  }

  componentWillMount(){
    this.setState({ showFlag: this.props.visible === 'visible'  });
  }

  handleToggle =()=> {

    this.setState({
      showFlag:!this.state.showFlag
    });
  }

  render() {

    return (
      <div>
        <h1>Flag: {this.state.showFlag ? '' : ''} </h1>

        <button className='list_toggle' onClick={this.handleToggle}>
          {this.state.showFlag ? 'Hide Flag': 'Show Flag'}
        </button>

        <hr/>

        Props:
        <pre>
          {JSON.stringify(this.props, null, 2)}
        </pre>
        State:
        <pre>
          {JSON.stringify(this.state, null, 2)}
        </pre>

      </div>
    );

  }
}

export default FlagTest

注意:我确实需要使用 getInitialProps 因为我打算在更复杂的情况下使用它(API 通过 id 获取),这里没有包括它因为不是与这个问题直接相关。

这是我的无服务器 YML

service: A123-serverless

provider:
  name: aws
  runtime: nodejs8.10
  stage: ${self:custom.secrets.NODE_ENV}
  region: us-west-2
  environment:
    NODE_ENV: ${self:custom.secrets.NODE_ENV}

functions:
  server:
    handler: index.server
    events:
      - http: ANY /
      - http: ANY /{proxy+}

plugins:
  - serverless-apigw-binary
  - serverless-domain-manager

custom:
  secrets: ${file(secrets.json)}
  apigwBinary:
    types:
      - '*/*'
  customDomain:
    domainName: ${self:custom.secrets.DOMAIN}
    basePath: ''
    stage: ${self:custom.secrets.NODE_ENV}
    createRoute53Record: true
    endpointType: 'regional'

谢谢!

我找到了我的问题的答案,张贴在这里,希望能帮助遇到同样问题的人:

问题是我使用 "query" 提取 'id',它在本地工作正常,但在使用 Express 的服务器端你需要像这样将其作为参数传递:

server.get("/q/:id", (req, res) => {
  return app.render(req, res, "/q/_tid", { id: req.params.id });
});

然后在 React 组件上你可以捕获它并使用它 getInitial Props as req.params.id

static async getInitialProps({ req }) {

      myId = req.params.id

}