【问题标题】:Why does this function in NextJS works locally, but not when deployed in AWS Lambda?为什么 NextJS 中的这个函数在本地工作,但在 AWS Lambda 中部署时却不行?
【发布时间】:2019-09-19 08:53:38
【问题描述】:

我已经对此进行了大量的测试和研究,但我根本无法弄清楚。我有一个功能在本地运行时运行良好(没有错误),但在部署为 AWS lambda 时失败。

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

本地网址http://localhost:3000/flagTest/visible(这很好用✅)

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

文件:/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 Fetching by 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'

谢谢!

【问题讨论】:

    标签: amazon-web-services aws-lambda next.js serverless-framework aws-serverless


    【解决方案1】:

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

    问题是我使用“查询”来提取“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
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-30
      • 2023-03-12
      • 2020-01-07
      • 2015-06-06
      • 2019-05-25
      • 2013-12-21
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多