- Create a new directory for the API tier
mkdir ../api
pushd ../api
npm install -g serverless
$ serverless create \
--template aws-nodejs \
--name $API_NAME
- Change the serverless.yml file:
- Update Node.JS
- Select region
- Select deployment stage name
- Enable Cross Origin Resource Sharing (CORS)
# serverless.yml
service: awsdevapi
provider:
name: aws
runtime: nodejs6.10
region: us-east-1
stage: prod
functions:
hello:
handler: handler.hello
events:
- http:
path: hello
method: get
cors: true
- Update function code in handler.js to return HTTP headers to be bypassed by lambda-proxy and computed message
'use strict';
module.exports.hello = function(event, context, callback) {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
},
body: JSON.stringify({ "message": "Hello World! 0.1+0.1+0.1="+(0.1+0.1+0.1) })
};
callback(null, response);
};
$ sls deploy
...
endpoints:
GET - https://cjxpxfejol.execute-api.us-east-1.amazonaws.com/prod/hello
...
$ curl -v https://cjxpxfejol.execute-api.us-east-1.amazonaws.com/prod/hello
* Trying 54.192.28.91...
* TCP_NODELAY set
* Connected to cjxpxfejol.execute-api.us-east-1.amazonaws.com (54.192.28.91) port 443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
* Server certificate: *.execute-api.us-east-1.amazonaws.com
* Server certificate: Symantec Class 3 Secure Server CA - G4
* Server certificate: VeriSign Class 3 Public Primary Certification Authority - G5
> GET /prod/hello HTTP/1.1
> Host: cjxpxfejol.execute-api.us-east-1.amazonaws.com
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 58
< Connection: keep-alive
< Date: Fri, 14 Jul 2017 13:20:35 GMT
< x-amzn-RequestId: 385e3d73-6897-11e7-97a9-493f386caa95
< Access-Control-Allow-Origin: *
< X-Amzn-Trace-Id: sampled=0;root=1-5968c523-5990b7de3ddfc518b194c172
< Access-Control-Allow-Credentials: true
< X-Cache: Miss from cloudfront
< Via: 1.1 22d1048cb75c81d8e25a9b2b49d5d6ab.cloudfront.net (CloudFront)
< X-Amz-Cf-Id: MGkOAl_DOLdc_V6JQvQgZ3CdlprTuK1Z0geRMeogO4Mrzv5ZTBYOhQ==
<
* Curl_http_done: called premature == 0
* Connection #0 to host cjxpxfejol.execute-api.us-east-1.amazonaws.com left intact
{"message":"Hello World! 0.1+0.1+0.1=0.30000000000000004"}