【问题标题】:Returning html from lambda function using express使用 express 从 lambda 函数返回 html
【发布时间】:2019-04-01 23:28:08
【问题描述】:

我创建了一个运行快速应用程序的 AWS Lambda。 express 应用程序有一个路由支持get 请求并返回一个简单的 HTML 页面。我使用awsServerlessExpress 运行它,但返回的不仅仅是 HTML,而是 JSON。

这是返回的内容:

{"statusCode":200,"body":"\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n
Testing!
\r\n
\r\n
This is a test

\r\n
\r\n\r\n\r\n","headers":{"x-powered-by":"Express","accept-ranges":"bytes","cache-control":"public, max-age=0","last-modified":"Sun, 28 Oct 2018 23:48:18 GMT","etag":"W/\"b3-166bd1405d0\"","content-type":"text/html; charset=UTF-8","content-length":"179","date":"Mon, 29 Oct 2018 03:57:27 GMT","connection":"close"},"isBase64Encoded":false}

我怎样才能让它只返回 HTML?

这是我的app.js

const express = require('express');
const app = express();
const router = express.Router();

app.use(express.static(__dirname + "/client"));


app.get('/', function(req, res) {
    res.set('Content-Type', 'text/html');
    res.sendFile(__dirname + '/client/index.html');
});

app.use('/', router);

module.exports = app;

这是我的index.js

'use strict'

const binaryMimeTypes = [
  'application/javascript',
  'application/json',
  'application/octet-stream',
  'application/xml',
  'font/eot',
  'font/opentype',
  'font/otf',
  'image/jpeg',
  'image/png',
  'image/svg+xml',
  'text/comma-separated-values',
  'text/css',
  'text/html',
  'text/javascript',
  'text/plain',
  'text/text',
  'text/xml',
  'multipart/form-data'
]

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

exports.handler = (event, context) => { awsServerlessExpress.proxy(server, event, context) }

在 AWS 中,我创建了一个以 API Gateway 作为触发器的新 Lambda。这是我的 API 网关的样子:

【问题讨论】:

    标签: javascript node.js amazon-web-services express aws-lambda


    【解决方案1】:

    您需要在 API Gateway 中启用 lambda 代理集成。 在Integration Request 设置中选中Use Lambda Proxy integration 框。

    aws-serverless-express 使用 lambda 代理来映射请求和响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-27
      • 2018-01-07
      • 2015-08-27
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多