Table of Contents
Your First Serverless Service
CORS Configuration
CORS Lambda Adjustment
Invoking the Function
Building a Practical Lambda
Implementing the Code
Optional: Bundling
Conclusion
Home Web Front-end CSS Tutorial Building Your First Serverless Service With AWS Lambda Functions

Building Your First Serverless Service With AWS Lambda Functions

Apr 05, 2025 am 10:10 AM

Building Your First Serverless Service With AWS Lambda Functions

Many developers have some familiarity with AWS Lambda functions. While relatively easy to set up, navigating the vast AWS ecosystem can be challenging. The sheer number of components makes it difficult to grasp the bigger picture and integrate Lambda functions smoothly into a standard web application.

The Serverless Framework simplifies this process considerably. It streamlines the creation, deployment, and—most importantly—the integration of Lambda functions into web applications. While its capabilities extend far beyond this, this article focuses on these core aspects. This introduction hopefully sparks your interest to explore Serverless's broader functionalities. If you're new to Lambda, consider reviewing this AWS introductory guide first.

The quick start guide provides the best instructions for initial installation and setup. Following it, you should be operational within 5-10 minutes, even if you need to create an AWS account.

Your First Serverless Service

Before diving into advanced features like file uploads and S3 buckets, let's create a basic Lambda function, connect it to an HTTP endpoint, and invoke it from an existing web application. The function won't perform any complex tasks, but it effectively demonstrates the ease of use of the Serverless Framework.

Begin by creating your service. In your web application (using create-react-app is a quick way to start a new one), create a directory for your services (e.g., a lambda folder). Navigate to this directory in your terminal and run:

sls create -t aws-nodejs --path hello-world
Copy after login

This creates a hello-world directory. Let's examine its contents.

handler.js contains an asynchronous function that returns a message. You could deploy this Lambda function immediately using sls deploy, making it invokable. However, let's first make it accessible via the web.

Manual AWS configuration would involve setting up an AWS API Gateway endpoint and stage, then configuring it to proxy to your Lambda. Serverless handles all this with minimal configuration.

Still in the hello-world directory, open serverless.yaml.

The configuration file includes boilerplate for common setups. Uncomment the HTTP entries and specify a more descriptive path:

functions:
  hello:
    handler: handler.hello
    events:
      - http:
        path: msg
        method: get
Copy after login

That's it. Serverless manages the underlying complexities.

CORS Configuration

To invoke the function from front-end JavaScript using the Fetch API, CORS configuration is necessary. This section outlines the process.

Add cors: true below the configuration:

functions:
  hello:
    handler: handler.hello
    events:
      - http:
        path: msg
        method: get
        cors: true
Copy after login

This configures CORS on the API endpoint, enabling cross-origin communication.

CORS Lambda Adjustment

While the HTTP endpoint is CORS-enabled, the Lambda function must return the appropriate headers. Let's automate this by modifying handler.js:

const CorsResponse = obj => ({
  statusCode: 200,
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "*",
    "Access-Control-Allow-Methods": "*"
  },
  body: JSON.stringify(obj)
});

module.exports.hello = async event => {
  return CorsResponse("HELLO, WORLD!");
};
Copy after login

Now, the Lambda function's response is processed through this function.

Run sls deploy from the hello-world directory to deploy the Lambda function.

The sls info command provides the function's URL, eliminating the need to manually locate it in the AWS console. The URL will resemble:

<code>https://6xpmc3g0ch.execute-api.us-east-1.amazonaws.com/dev/msg</code>
Copy after login

Invoking the Function

Now, let's invoke the function from a web application using Fetch:

fetch("https://6xpmc3g0ch.execute-api.us-east-1.amazonaws.com/dev/msg")
  .then(resp => resp.json())
  .then(resp => {
    console.log(resp);
  });
Copy after login

The message should appear in the browser's developer console.

Let's repeat this process, creating a more practical function: a Lambda that resizes images and uploads them to an S3 bucket. Instead of triggering on S3 uploads, the user uploads directly to the Lambda, eliminating the need for client-side AWS SDK resources.

Building a Practical Lambda

Let's create a new service (e.g., cover-art):

sls create -t aws-nodejs --path cover-art
Copy after login

Add the HTTP endpoint path (POST method for file uploads) and enable CORS:

events:
  - http:
    path: upload
    method: post
    cors: true
Copy after login

Grant the Lambda access to your S3 bucket(s) by uncommenting and modifying the iamRoleStatements section in serverless.yaml:

iamRoleStatements:
  - Effect: "Allow"
    Action:
      - "s3:*"
    Resource: ["arn:aws:s3:::your-bucket-name/*"]
Copy after login

Configure the API Gateway to accept multipart/form-data:

provider:
  name: aws
  runtime: nodejs12.x
  apiGateway:
    binaryMediaTypes:
      - 'multipart/form-data'
Copy after login

Rename the function in serverless.yaml and handler.js to upload.

Implementing the Code

Install required packages:

npm i jimp uuid lambda-multipart-parser
Copy after login

Implement an S3 upload helper function and the main upload function in handler.js (the complete code is too extensive to include here, but it's available in the original prompt).

Use a library like react-dropzone on the client-side to handle file uploads (example code provided in the original prompt).

Optional: Bundling

Bundling your code reduces deployment size and improves performance. Install serverless-webpack:

npm i serverless-webpack --save-dev
Copy after login

Add it to serverless.yaml:

plugins:
  - serverless-webpack
Copy after login

Create webpack.config.js (configuration provided in the original prompt). Redeploy to utilize webpack.

Conclusion

The Serverless Framework significantly simplifies the development and deployment of AWS Lambda functions. This introduction provides a foundation for further exploration of its capabilities. The resources mentioned in the original prompt offer valuable learning opportunities for deeper understanding.

The above is the detailed content of Building Your First Serverless Service With AWS Lambda Functions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Google Fonts   Variable Fonts Google Fonts Variable Fonts Apr 09, 2025 am 10:42 AM

I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

How to Create an Animated Countdown Timer With HTML, CSS and JavaScript How to Create an Animated Countdown Timer With HTML, CSS and JavaScript Apr 11, 2025 am 11:29 AM

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

HTML Data Attributes Guide HTML Data Attributes Guide Apr 11, 2025 am 11:50 AM

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

How We Created a Static Site That Generates Tartan Patterns in SVG How We Created a Static Site That Generates Tartan Patterns in SVG Apr 09, 2025 am 11:29 AM

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan

How to Build Vue Components in a WordPress Theme How to Build Vue Components in a WordPress Theme Apr 11, 2025 am 11:03 AM

The inline-template directive allows us to build rich Vue components as a progressive enhancement over existing WordPress markup.

PHP is A-OK for Templating PHP is A-OK for Templating Apr 11, 2025 am 11:04 AM

PHP templating often gets a bad rap for facilitating subpar code — but that doesn&#039;t have to be the case. Let’s look at how PHP projects can enforce a basic

A Comparison of Static Form Providers A Comparison of Static Form Providers Apr 16, 2025 am 11:20 AM

Let’s attempt to coin a term here: "Static Form Provider." You bring your HTML

See all articles