Ócáid
Tóg Feidhmchláir agus Gníomhairí AI
Mar 17, 9 PM - Mar 21, 10 AM
Bí ar an tsraith meetup chun réitigh AI inscálaithe a thógáil bunaithe ar chásanna úsáide fíor-dhomhanda le forbróirí agus saineolaithe eile.
Cláraigh anoisNí thacaítear leis an mbrabhsálaí seo a thuilleadh.
Uasghrádú go Microsoft Edge chun leas a bhaint as na gnéithe is déanaí, nuashonruithe slándála, agus tacaíocht theicniúil.
In this article, you use command-line tools to create a JavaScript function that responds to HTTP requests. After testing the code locally, you deploy it to the serverless environment of Azure Functions.
Tábhachtach
The content of this article changes based on your choice of the Node.js programming model in the selector at the top of the page. The v4 model is generally available and is designed to have a more flexible and intuitive experience for JavaScript and TypeScript developers. Learn more about the differences between v3 and v4 in the migration guide.
Completion of this quickstart incurs a small cost of a few USD cents or less in your Azure account.
There's also a Visual Studio Code-based version of this article.
Before you begin, you must have the following prerequisites:
An Azure account with an active subscription. Create an account for free.
One of the following tools for creating Azure resources:
Azure CLI version 2.4 or later.
The Azure Az PowerShell module version 5.9.0 or later.
The recommended way to install Core Tools depends on the operating system of your local development computer.
The following steps use APT to install Core Tools on your Ubuntu/Debian Linux distribution. For other Linux distributions, see the Core Tools readme.
Install the Microsoft package repository GPG key, to validate package integrity:
curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg
Set up the APT source list before doing an APT update.
sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-$(lsb_release -cs 2>/dev/null)-prod $(lsb_release -cs 2>/dev/null) main" > /etc/apt/sources.list.d/dotnetdev.list'
sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/debian/$(lsb_release -rs 2>/dev/null | cut -d'.' -f 1)/prod $(lsb_release -cs 2>/dev/null) main" > /etc/apt/sources.list.d/dotnetdev.list'
Check the /etc/apt/sources.list.d/dotnetdev.list
file for one of the appropriate Linux version strings in the following table:
Linux distribution | Version |
---|---|
Debian 12 | bookworm |
Debian 11 | bullseye |
Debian 10 | buster |
Debian 9 | stretch |
Ubuntu 24.04 | noble |
Ubuntu 22.04 | jammy |
Ubuntu 20.04 | focal |
Ubuntu 19.04 | disco |
Ubuntu 18.10 | cosmic |
Ubuntu 18.04 | bionic |
Ubuntu 17.04 | zesty |
Ubuntu 16.04/Linux Mint 18 | xenial |
Start the APT source update:
sudo apt-get update
Install the Core Tools package:
sudo apt-get install azure-functions-core-tools-4
In Azure Functions, a function project is a container for one or more individual functions that each responds to a specific trigger. All functions in a project share the same local and hosting configurations. In this section, you create a function project that contains a single function.
In a suitable folder, run the func init
command, as follows, to create a JavaScript Node.js v3 project in the current folder:
func init --javascript --model V3
This folder now contains various files for the project, including configurations files named local.settings.json and host.json. Because local.settings.json can contain secrets downloaded from Azure, the file is excluded from source control by default in the .gitignore file.
Add a function to your project by using the following command, where the --name
argument is the unique name of your function (HttpExample) and the --template
argument specifies the function's trigger (HTTP).
func new --name HttpExample --template "HTTP trigger" --authlevel "anonymous"
The func new
command creates a subfolder matching the function name that contains a code file appropriate to the project's chosen language and a configuration file named function.json.
You may find the Azure Functions Core Tools reference helpful.
If desired, you can skip to Run the function locally and examine the file contents later.
index.js exports a function that's triggered according to the configuration in function.json.
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
const name = (req.query.name || (req.body && req.body.name));
const responseMessage = name
? "Hello, " + name + ". This HTTP triggered function executed successfully."
: "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";
context.res = {
// status: 200, /* Defaults to 200 */
body: responseMessage
};
}
For an HTTP trigger, the function receives request data in the variable req
as defined in function.json. The response is defined as res
in function.json and can be accessed using context.res
. To learn more, see Azure Functions HTTP triggers and bindings.
function.json is a configuration file that defines the input and output bindings
for the function, including the trigger type.
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
Each binding requires a direction, a type, and a unique name. The HTTP trigger has an input binding of type httpTrigger
and output binding of type http
.
In a suitable folder, run the func init
command, as follows, to create a JavaScript Node.js v4 project in the current folder:
func init --javascript
This folder now contains various files for the project, including configurations files named local.settings.json and host.json. Because local.settings.json can contain secrets downloaded from Azure, the file is excluded from source control by default in the .gitignore file. Required npm packages are also installed in node_modules.
Add a function to your project by using the following command, where the --name
argument is the unique name of your function (HttpExample) and the --template
argument specifies the function's trigger (HTTP).
func new --name HttpExample --template "HTTP trigger" --authlevel "anonymous"
[`func new`](functions-core-tools-reference.md#func-new) creates a file named *HttpExample.js* in the *src/functions* directory, which contains your function's code.
Add Azure Storage connection information in local.settings.json.
{
"Values": {
"AzureWebJobsStorage": "<Azure Storage connection information>",
"FUNCTIONS_WORKER_RUNTIME": "node"
}
}
(Optional) If you want to learn more about a particular function, say HTTP trigger, you can run the following command:
func help httptrigger
Run your function by starting the local Azure Functions runtime host from the LocalFunctionProj folder.
func start
Toward the end of the output, the following lines must appear:
Nóta
If HttpExample doesn't appear as shown above, you likely started the host from outside the root folder of the project. In that case, use Ctrl+C to stop the host, go to the project's root folder, and run the previous command again.
Copy the URL of your HTTP function from this output to a browser and append the query string ?name=<YOUR_NAME>
, making the full URL like http://localhost:7071/api/HttpExample?name=Functions
. The browser should display a response message that echoes back your query string value. The terminal in which you started your project also shows log output as you make requests.
When you're done, press Ctrl + C and type y
to stop the functions host.
Before you can deploy your function code to Azure, you need to create three resources:
Use the following commands to create these items. Both Azure CLI and PowerShell are supported.
If you haven't done so already, sign in to Azure:
az login
The az login command signs you into your Azure account.
Create a resource group named AzureFunctionsQuickstart-rg
in your chosen region:
az group create --name AzureFunctionsQuickstart-rg --location <REGION>
The az group create command creates a resource group. In the above command, replace <REGION>
with a region near you, using an available region code returned from the az account list-locations command.
Create a general-purpose storage account in your resource group and region:
az storage account create --name <STORAGE_NAME> --location <REGION> --resource-group AzureFunctionsQuickstart-rg --sku Standard_LRS --allow-blob-public-access false
The az storage account create command creates the storage account.
In the previous example, replace <STORAGE_NAME>
with a name that is appropriate to you and unique in Azure Storage. Names must contain three to 24 characters numbers and lowercase letters only. Standard_LRS
specifies a general-purpose account, which is supported by Functions.
Tábhachtach
The storage account is used to store important app data, sometimes including the application code itself. You should limit access from other apps and users to the storage account.
Create the function app in Azure:
az functionapp create --resource-group AzureFunctionsQuickstart-rg --consumption-plan-location <REGION> --runtime node --runtime-version 18 --functions-version 4 --name <APP_NAME> --storage-account <STORAGE_NAME>
The az functionapp create command creates the function app in Azure. It's recommended that you use the latest LTS version of Node.js, which is currently 18. You can specify the version by setting --runtime-version
to 18
.
In the previous example, replace <STORAGE_NAME>
with the name of the account you used in the previous step, and replace <APP_NAME>
with a globally unique name appropriate to you. The <APP_NAME>
is also the default DNS domain for the function app.
This command creates a function app running in your specified language runtime under the Azure Functions Consumption Plan, which is free for the amount of usage you incur here. The command also creates an associated Azure Application Insights instance in the same resource group, with which you can monitor your function app and view logs. For more information, see Monitor Azure Functions. The instance incurs no costs until you activate it.
After you've successfully created your function app in Azure, you're now ready to deploy your local functions project by using the func azure functionapp publish
command.
In your root project folder, run this func azure functionapp publish
command:
func azure functionapp publish <APP_NAME>
In this example, replace <APP_NAME>
with the name of your app. A successful deployment shows results similar to the following output (truncated for simplicity):
... Getting site publishing info... Creating archive for current directory... Performing remote build for functions project. ... Deployment successful. Remote build succeeded! Syncing triggers... Functions in msdocs-azurefunctions-qs: HttpExample - [httpTrigger] Invoke url: https://msdocs-azurefunctions-qs.azurewebsites.net/api/httpexample
Because your function uses an HTTP trigger, you invoke it by making an HTTP request to its URL in the browser or with a tool like curl.
Copy the complete Invoke URL shown in the output of the publish command into a browser address bar, appending the query parameter ?name=Functions
. The browser should display similar output as when you ran the function locally.
Run the following command to view near real-time streaming logs:
func azure functionapp logstream <APP_NAME>
In a separate terminal window or in the browser, call the remote function again. A verbose log of the function execution in Azure is shown in the terminal.
If you continue to the next step and add an Azure Storage queue output binding, keep all your resources in place as you'll build on what you've already done.
Otherwise, use the following command to delete the resource group and all its contained resources to avoid incurring further costs.
az group delete --name AzureFunctionsQuickstart-rg
Ócáid
Tóg Feidhmchláir agus Gníomhairí AI
Mar 17, 9 PM - Mar 21, 10 AM
Bí ar an tsraith meetup chun réitigh AI inscálaithe a thógáil bunaithe ar chásanna úsáide fíor-dhomhanda le forbróirí agus saineolaithe eile.
Cláraigh anoisOiliúint
Cosán foghlama
Create serverless applications learning path - Training
In this learning path, discover Azure Functions that create event-driven, compute-on-demand systems using server-side logic to build serverless architectures.
Deimhniú
Microsoft Certified: Azure Developer Associate - Certifications
Build end-to-end solutions in Microsoft Azure to create Azure Functions, implement and manage web apps, develop solutions utilizing Azure storage, and more.