• 主页
  • 在使用express.static时,如何在aws lambda和aws sam中不返回express中的json

在使用express.static时,如何在aws lambda和aws sam中不返回express中的json

我正在使用aws lambda和aws的sma cli工具制作一个无服务器网站(主要是为了测试对api的真正请求)。我想使用express.static函数为资产提供服务,但遇到了一个问题。当我使用它时,我得到了一个关于它没有返回json的错误,这个错误告诉我它需要这样做才能工作。我现在有两个函数:视图(为ejs文件提供服务)和资源(为静态文件提供服务,如css和前端js)。这是我的template.yml:

# This is the SAM template that represents the architecture of your serverless application
# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html

# The AWSTemplateFormatVersion identifies the capabilities of the template
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/format-version-structure.html
AWSTemplateFormatVersion: 2010-09-09
Description: >-
  [Description goes here]

# Transform section specifies one or more macros that AWS CloudFormation uses to process your template
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-section-structure.html
Transform:
- AWS::Serverless-2016-10-31

# Resources declares the AWS resources that you want to include in the stack
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html
Resources:
  assets:
    Type: AWS::Serverless::Function
    Properties:
      Handler: amplify/backend/function/assets/src/index.handler
      Runtime: nodejs14.x
      MemorySize: 512
      Timeout: 100
      Description: serves the assets
      Events:
        Api:
          Type: Api
          Properties:
            Path: /assets/{folder}/{file}
            Method: GET
  views:
    Type: AWS::Serverless::Function
    Properties:
      Handler: amplify/backend/function/views/src/index.handler
      Runtime: nodejs14.x
      MemorySize: 512
      Timeout: 100
      Description: serves the views
      Events:
        Api:
          Type: Api
          Properties:
            Path: /
            Method: GET

Outputs:
  WebEndpoint:
    Description: "API Gateway endpoint URL for Prod stage"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"

我的assets函数的代码是: index.js:

const awsServerlessExpress = require('aws-serverless-express');
const app = require('./app');

const server = awsServerlessExpress.createServer(app);

exports.handler = (event, context) => {
  console.log(`EVENT: ${JSON.stringify(event)}`);
  return awsServerlessExpress.proxy(server, event, context, 'PROMISE').promise;
};

app.js:

const express = require('express'),

    app = express()
app.use(express.json())
app.use('/assets', express.static('assets'))

app.listen(3000);

module.exports = app

是否有一些我应该知道的template.yml配置选项,或者我必须更改我的代码?

转载请注明出处:http://www.bigbigcall.com/article/20230331/1423971.html