Skip to content

Commit 2871acb

Browse files
committed
fix: decodes base64 requests (fixes #64); added form to index view to showcase POST/PUT; move example instructions to example/README.md; update example to Node.js 6.10; added app.local.js to easily run local express
1 parent 6ba1029 commit 2871acb

File tree

9 files changed

+160
-97
lines changed

9 files changed

+160
-97
lines changed

README.md

Lines changed: 12 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -18,45 +18,25 @@ exports.handler = (event, context) => awsServerlessExpress.proxy(server, event,
1818

1919
[Package and create your Lambda function](http://docs.aws.amazon.com/lambda/latest/dg/nodejs-create-deployment-pkg.html), then configure a simple proxy API using Amazon API Gateway and integrate it with your Lambda function.
2020

21-
## Example
21+
## Quick Start/Example
2222

23-
In addition to a basic Lambda function and Express server, the `example` directory includes a [Swagger file](http://swagger.io/specification/), [CloudFormation template](https://aws.amazon.com/cloudformation/aws-cloudformation-templates/) with [Serverless Application Model (SAM)](https://github.com/awslabs/serverless-application-model), and helper scripts to help you set up and manage your application.
23+
Want to get up and running quickly? [Check out our example](example/README.md) which includes:
2424

25-
### Steps for running the example
26-
This guide assumes you have already [set up an AWS account](http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/AboutAWSAccounts.html) and have the latest version of the [AWS CLI](https://aws.amazon.com/cli/) installed.
27-
28-
1. From your preferred project directory: `git clone https://github.com/awslabs/aws-serverless-express.git && cd aws-serverless-express/example`.
29-
2. Run `npm run config -- --account-id="<accountId>" --bucket-name="<bucketName>" [--region="<region>" --function-name="<functionName>"]` to configure the example, eg. `npm run config -- --account-id="123456789012" --bucket-name="my-bucket" --region="us-west-2" --function-name="my-function"`. This modifies `package.json`, `simple-proxy-api.yaml` and `cloudformation.yaml` with your account ID, bucket, region and function name (region defaults to `us-east-1` and function name defaults to `AwsServerlessExpressFunction`). If the bucket you specify does not yet exist, the next step will create it for you. This step modifies the existing files in-place; if you wish to make changes to these settings, you will need to modify `package.json`, `simple-proxy-api.yaml` and `cloudformation.yaml` manually.
30-
3. Run `npm run setup` (Windows users: `npm run win-setup`) - this installs the node dependencies, creates an S3 bucket (if it does not already exist), packages and deploys your serverless Express application to AWS Lambda, and creates an API Gateway proxy API.
31-
4. After the setup command completes, open the AWS CloudFormation console https://console.aws.amazon.com/cloudformation/home and switch to the region you specified. Select the `AwsServerlessExpressStack` stack, then click the `ApiUrl` value under the __Outputs__ section - this will open a new page with your running API. The API index lists the resources available in the example Express server (`app.js`), along with example `curl` commands.
32-
33-
See the sections below for details on how to migrate an existing (or create a new) Node.js project based on this example. If you would prefer to delete AWS assets that were just created, simply run `npm run delete-stack` to delete the CloudFormation Stack, including the API and Lambda Function. If you specified a new bucket in the `config` command for step 1 and want to delete that bucket, run `npm run delete-bucket`.
34-
35-
### Creating or migrating a Node.js project based on the example
36-
37-
To use this example as a base for a new Node.js project:
38-
39-
1. Copy the files in the `example` directory into a new project directory (`cp -r ./example ~/projects/my-new-node-project`). If you have not already done so, follow the [steps for running the example](#steps-for-running-the-example) (you may want to first modify some of the resource names to something more project-specific, eg. the CloudFormation stack, Lambda function, and API Gateway API).
40-
2. After making updates to `app.js`, simply run `npm run package-deploy` (Windows users: `npm run win-package-deploy`).
41-
42-
To migrate an existing Node server:
43-
44-
1. Copy the following files from the `example` directory: `api-gateway-event.json`, `cloudformation.yaml`, `lambda.js`, and `simple-proxy-api.yaml`. Additionally, copy the `scripts` and `config` sections of `example/package.json` into your existing `package.json` - this includes many helpful commands to manage your AWS serverless assets and perform _basic_ local simulation of API Gateway and Lambda. If you have not already done so, follow the [steps for running the example](#steps-for-running-the-example) (be sure to copy over `scripts/configure.js`. You may want to first modify some of the resource names to something more project-specific, eg. the CloudFormation stack, Lambda function, and API Gateway API).
45-
2. From your existing project directory, run `npm install --save aws-serverless-express`.
46-
3. Modify `lambda.js` to import your own server configuration (eg. change `require('./app')` to `require('./server')`). You will need to ensure you export your app configuration from the necessary file (eg. `module.exports = app`). This library takes your app configuration and listens on a Unix Domain Socket for you, so you can remove your call to `app.listen()` (if you have a `server.listen` callback, you can provide it as the second parameter in the `awsServerlessExpress.createServer` method).
47-
4. Modify the `CodeUri` property of the Lambda function resource in `cloudformation.yaml` to point to your application directory (e.g. `CodeUri: ./src`). If you are using a build tool (e.g. Gulp, Grunt, Webpack, Rollup, etc.), you will instead want to point to your build output directory.
48-
5. Run `npm run package-deploy` (Windows users: `npm run win-package-deploy`) to package and deploy your application.
49-
50-
To perform a basic, local simulation of API Gateway and Lambda with your Node server, update `api-gateway-event.json` with some values that are valid for your server (`httpMethod`, `path`, `body` etc.) and run `npm run local`. AWS Lambda uses NodeJS 4.3 LTS, and it is recommended to use the same version for testing purposes.
51-
52-
If you need to make modifications to your API Gateway API, modify `simple-proxy-api.yaml` and run `npm run package-deploy`. If your API requires CORS, be sure to modify the two `options` methods defined in the Swagger file, otherwise you can safely remove them. To modify your other AWS assets, make your changes to `cloudformation.yaml` and run `npm run package-deploy`. Alternatively, you can manage these assets via the AWS console.
25+
- Lambda function
26+
- Express server
27+
[Swagger file](http://swagger.io/specification/)
28+
- [Serverless Application Model (SAM)](https://github.com/awslabs/serverless-application-model)/[CloudFormation](https://aws.amazon.com/cloudformation/aws-cloudformation-templates/) template
29+
- Helper scripts to configure, deploy, and manage your application
5330

5431
### Getting the API Gateway event object
5532
This package includes middleware to easily get the event object Lambda receives from API Gateway
5633

5734
```js
5835
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
5936
app.use(awsServerlessExpressMiddleware.eventContext())
37+
app.get('/', (req, res) => {
38+
res.json(req.apiGateway.event)
39+
})
6040
```
6141

6242
### Is AWS serverless right for my app?
@@ -72,12 +52,12 @@ app.use(awsServerlessExpressMiddleware.eventContext())
7252
- [Staging](http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-deploy-api.html)
7353
- [SDK Generation](http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-generate-sdk.html)
7454
- [API Monitoring](http://docs.aws.amazon.com/apigateway/latest/developerguide/monitoring-cloudwatch.html)
55+
- [Request Validation](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-method-request-validation.html)
56+
- [Documentation](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-documenting-api.html)
7557

7658
#### Cons
7759

78-
- Currently limited to Node.js 4.3 (LTS)
7960
- For apps that may not see traffic for several minutes at a time, you could see [cold starts](https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/)
80-
- May be more expensive for high-traffic apps
8161
- Cannot use native libraries (aka [Addons](https://nodejs.org/api/addons.html)) unless you package your app on an EC2 machine running Amazon Linux
8262
- Stateless only
8363
- API Gateway has a timeout of 30 seconds, and Lambda has a maximum execution time of 5 minutes.

example/README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
## Example
2+
3+
In addition to a basic Lambda function and Express server, the `example` directory includes a [Swagger file](http://swagger.io/specification/), [CloudFormation template](https://aws.amazon.com/cloudformation/aws-cloudformation-templates/) with [Serverless Application Model (SAM)](https://github.com/awslabs/serverless-application-model), and helper scripts to help you set up and manage your application.
4+
5+
### Steps for running the example
6+
This guide assumes you have already [set up an AWS account](http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/AboutAWSAccounts.html) and have the latest version of the [AWS CLI](https://aws.amazon.com/cli/) installed.
7+
8+
1. From your preferred project directory: `git clone https://github.com/awslabs/aws-serverless-express.git && cd aws-serverless-express/example`.
9+
2. Run `npm run config -- --account-id="<accountId>" --bucket-name="<bucketName>" [--region="<region>" --function-name="<functionName>"]` to configure the example, eg. `npm run config -- --account-id="123456789012" --bucket-name="my-unique-bucket"`. This modifies `package.json`, `simple-proxy-api.yaml` and `cloudformation.yaml` with your account ID, bucket, region and function name (region defaults to `us-east-1` and function name defaults to `AwsServerlessExpressFunction`). If the bucket you specify does not yet exist, the next step will create it for you. This step modifies the existing files in-place; if you wish to make changes to these settings, you will need to modify `package.json`, `simple-proxy-api.yaml` and `cloudformation.yaml` manually.
10+
3. Run `npm run setup` (Windows users: `npm run win-setup`) - this installs the node dependencies, creates an S3 bucket (if it does not already exist), packages and deploys your serverless Express application to AWS Lambda, and creates an API Gateway proxy API.
11+
4. After the setup command completes, open the AWS CloudFormation console https://console.aws.amazon.com/cloudformation/home and switch to the region you specified. Select the `AwsServerlessExpressStack` stack, then click the `ApiUrl` value under the __Outputs__ section - this will open a new page with your running API. The API index lists the resources available in the example Express server (`app.js`), along with example `curl` commands.
12+
13+
See the sections below for details on how to migrate an existing (or create a new) Node.js project based on this example. If you would prefer to delete AWS assets that were just created, simply run `npm run delete-stack` to delete the CloudFormation Stack, including the API and Lambda Function. If you specified a new bucket in the `config` command for step 1 and want to delete that bucket, run `npm run delete-bucket`.
14+
15+
### Creating or migrating a Node.js project based on the example
16+
17+
To use this example as a base for a new Node.js project:
18+
19+
1. Copy the files in the `example` directory into a new project directory (`cp -r ./example ~/projects/my-new-node-project`). If you have not already done so, follow the [steps for running the example](#steps-for-running-the-example) (you may want to first modify some of the resource names to something more project-specific, eg. the CloudFormation stack, Lambda function, and API Gateway API).
20+
2. After making updates to `app.js`, simply run `npm run package-deploy` (Windows users: `npm run win-package-deploy`).
21+
22+
To migrate an existing Node server:
23+
24+
1. Copy the following files from the `example` directory: `api-gateway-event.json`, `cloudformation.yaml`, `lambda.js`, and `simple-proxy-api.yaml`. Additionally, copy the `scripts` and `config` sections of `example/package.json` into your existing `package.json` - this includes many helpful commands to manage your AWS serverless assets and perform _basic_ local simulation of API Gateway and Lambda. If you have not already done so, follow the [steps for running the example](#steps-for-running-the-example) (be sure to copy over `scripts/configure.js`. You may want to first modify some of the resource names to something more project-specific, eg. the CloudFormation stack, Lambda function, and API Gateway API).
25+
2. From your existing project directory, run `npm install --save aws-serverless-express`.
26+
3. Modify `lambda.js` to import your own server configuration (eg. change `require('./app')` to `require('./server')`). You will need to ensure you export your app configuration from the necessary file (eg. `module.exports = app`). This library takes your app configuration and listens on a Unix Domain Socket for you, so you can remove your call to `app.listen()` (if you have a `server.listen` callback, you can provide it as the second parameter in the `awsServerlessExpress.createServer` method).
27+
4. Modify the `CodeUri` property of the Lambda function resource in `cloudformation.yaml` to point to your application directory (e.g. `CodeUri: ./src`). If you are using a build tool (e.g. Gulp, Grunt, Webpack, Rollup, etc.), you will instead want to point to your build output directory.
28+
5. Run `npm run package-deploy` (Windows users: `npm run win-package-deploy`) to package and deploy your application.
29+
30+
To perform a basic, local simulation of API Gateway and Lambda with your Node server, update `api-gateway-event.json` with some values that are valid for your server (`httpMethod`, `path`, `body` etc.) and run `npm run local`. AWS Lambda uses NodeJS 4.3 LTS, and it is recommended to use the same version for testing purposes.
31+
32+
If you need to make modifications to your API Gateway API, modify `simple-proxy-api.yaml` and run `npm run package-deploy`. If your API requires CORS, be sure to modify the two `options` methods defined in the Swagger file, otherwise you can safely remove them. To modify your other AWS assets, make your changes to `cloudformation.yaml` and run `npm run package-deploy`. Alternatively, you can manage these assets via the AWS console.
33+
34+
## Node.js version
35+
36+
This example was written against Node.js version 6.10

example/app.js

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -14,64 +14,64 @@ app.use(bodyParser.urlencoded({ extended: true }))
1414
app.use(awsServerlessExpressMiddleware.eventContext())
1515

1616
app.get('/', (req, res) => {
17-
res.render('index', {
18-
apiUrl: `https://${req.apiGateway.event.headers.Host}/${req.apiGateway.event.requestContext.stage}`
19-
})
17+
res.render('index', {
18+
apiUrl: req.apiGateway ? `https://${req.apiGateway.event.headers.Host}/${req.apiGateway.event.requestContext.stage}` : 'http://localhost:3000'
19+
})
2020
})
2121

2222
app.get('/sam', (req, res) => {
23-
res.sendFile(`${__dirname}/sam-logo.png`)
23+
res.sendFile(`${__dirname}/sam-logo.png`)
2424
})
2525

2626
app.get('/users', (req, res) => {
27-
res.json(users)
27+
res.json(users)
2828
})
2929

3030
app.get('/users/:userId', (req, res) => {
31-
const user = getUser(req.params.userId)
31+
const user = getUser(req.params.userId)
3232

33-
if (!user) return res.status(404).json({})
33+
if (!user) return res.status(404).json({})
3434

35-
return res.json(user)
35+
return res.json(user)
3636
})
3737

3838
app.post('/users', (req, res) => {
39-
const user = {
40-
id: ++userIdCounter,
41-
name: req.body.name
42-
}
43-
users.push(user)
44-
res.status(201).json(user)
39+
const user = {
40+
id: ++userIdCounter,
41+
name: req.body.name
42+
}
43+
users.push(user)
44+
res.status(201).json(user)
4545
})
4646

4747
app.put('/users/:userId', (req, res) => {
48-
const user = getUser(req.params.userId)
48+
const user = getUser(req.params.userId)
4949

50-
if (!user) return res.status(404).json({})
50+
if (!user) return res.status(404).json({})
5151

52-
user.name = req.body.name
53-
res.json(user)
52+
user.name = req.body.name
53+
res.json(user)
5454
})
5555

5656
app.delete('/users/:userId', (req, res) => {
57-
const userIndex = getUserIndex(req.params.userId)
57+
const userIndex = getUserIndex(req.params.userId)
5858

59-
if(userIndex === -1) return res.status(404).json({})
59+
if(userIndex === -1) return res.status(404).json({})
6060

61-
users.splice(userIndex, 1)
62-
res.json(users)
61+
users.splice(userIndex, 1)
62+
res.json(users)
6363
})
6464

6565
const getUser = (userId) => users.find(u => u.id === parseInt(userId))
6666
const getUserIndex = (userId) => users.findIndex(u => u.id === parseInt(userId))
6767

6868
// Ephemeral in-memory data store
6969
const users = [{
70-
id: 1,
71-
name: 'Joe'
70+
id: 1,
71+
name: 'Joe'
7272
}, {
73-
id: 2,
74-
name: 'Jane'
73+
id: 2,
74+
name: 'Jane'
7575
}]
7676
let userIdCounter = users.length
7777

example/app.local.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
const app = require('./app')
2+
const port = 3000
3+
4+
app.listen(port)
5+
console.log(`listening on http://localhost:${port}`)

example/cloudformation.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ Resources:
5757
Handler: lambda.handler
5858
MemorySize: 1024
5959
Role: !GetAtt LambdaExecutionRole.Arn
60-
Runtime: nodejs4.3
60+
Runtime: nodejs6.10
6161
Timeout: 30
6262
Events:
6363
ProxyApiRoot:

example/lambda.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
'use strict'
22
const awsServerlessExpress = require('aws-serverless-express')
33
const app = require('./app')
4+
45
// NOTE: If you get ERR_CONTENT_DECODING_FAILED in your browser, this is likely
56
// due to a compressed response (e.g. gzip) which has not been handled correctly
67
// by aws-serverless-express and/or API Gateway. Add the necessary MIME types to
7-
// binaryMimeTypes, and to the x-amazon-apigateway-binary-media-types array in
8-
// simple-proxy-api.yaml, then redeploy (`npm run package-deploy`)
8+
// binaryMimeTypes below, then redeploy (`npm run package-deploy`)
99
const binaryMimeTypes = [
1010
'application/javascript',
1111
'application/json',

example/simple-proxy-api.yaml

Lines changed: 1 addition & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -96,23 +96,7 @@ paths:
9696
application/json: "{\"statusCode\": 200}"
9797
type: mock
9898
x-amazon-apigateway-binary-media-types:
99-
- application/javascript
100-
- application/json
101-
- application/octet-stream
102-
- application/xml
103-
- font/eot
104-
- font/opentype
105-
- font/otf
106-
- image/jpeg
107-
- image/png
108-
- image/svg+xml
109-
- text/comma-separated-values
110-
- text/css
111-
- text/html
112-
- text/javascript
113-
- text/plain
114-
- text/text
115-
- text/xml
99+
- '*/*'
116100
definitions:
117101
Empty:
118102
type: object

0 commit comments

Comments
 (0)