GetProducts page displays 'Hello World!' instead of a json of the products

Munson, Gabrielle 0 Reputation points
2024-05-20T14:53:38.9+00:00

I'm working on the 'Build Serverless APIs with Azure Functions' training, and I am currently stuck on unit 6. After setting up the connection string, you're prompted to start the project and go to the GetProducts url. When I do that, my page only displays 'Hello World!' and not the json that is shown in the example image. Going back through the previous units, I never notice being prompted to edit the GetProducts file so I am confused on how I would even get the json. Any help would be greatly appreciated.

Azure Training
Azure Training
Azure: A cloud computing platform and infrastructure for building, deploying and managing applications and services through a worldwide network of Microsoft-managed datacenters.Training: Instruction to develop new skills.
1,092 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Srinud 1,810 Reputation points Microsoft Vendor
    2024-05-21T16:28:49.3733333+00:00

    Hi Munson, Gabrielle,

    We are thankful for your patience and understanding.

    Given that you were not prompted to edit the GetProducts file in the previous units, it seems there might be an assumption that the GetProducts function has been pre-implemented in the training module. However, if you only see "Hello World!" when hitting the /api/GetProducts endpoint, this suggests that either the implementation is missing or incorrect.

     Let's go through a step-by-step process to ensure your GetProducts endpoint is set up correctly to fetch and return the product data from your Cosmos DB.

    Step 1: Locate and Verify GetProducts Function

     1. Locate the Function

        - Find the GetProducts function file. It is typically located in a path similar to ./api/src/functions/GetProducts.ts.

    1. Verify the Content

        - Open this file and check its content. It should ideally contain logic to query the Cosmos DB and return the products.

    Step 2: Implement the GetProducts Function (if not already implemented)

    If the GetProducts function is not implemented, you can follow this example to query Cosmos DB and return the product data.

     1. Ensure Necessary Imports

        - Make sure you have the required imports at the top of your file:

    
        import { AzureFunction, Context, HttpRequest } from "@azure/functions";
    
        import { CosmosClient } from "@azure/cosmos";
    
        ```
    
    2. Initialize Cosmos DB Client:
    
        - Use the connection string from your environment settings to initialize the Cosmos DB client.
    
     ```typescript
    
        const CONNECTION_STRING = process.env.CONNECTION_STRING;
    
        const client = new CosmosClient(CONNECTION_STRING);
    
        const databaseId = "YourDatabaseId"; // Replace with your actual database ID
    
        const containerId = "YourContainerId"; // Replace with your actual container ID
    
        ```
    
    3. Implement the Function Logic:
    
        - Implement the function to query the Cosmos DB and return the data:
    
     
    
        ```typescript
    
        const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    
            context.log('GetProducts function processed a request.');
    
     
    
            const container = client.database(databaseId).container(containerId);
    
            const querySpec = {
    
                query: "SELECT * from c" // Adjust the query as necessary
    
            };
    
     
    
            try {
    
                const { resources: items } = await container.items.query(querySpec).fetchAll();
    
                context.res = {
    
                    status: 200,
    
                    body: items
    
                };
    
            } catch (error) {
    
                context.log('Error occurred:', error);
    
                context.res = {
    
                    status: 500,
    
                    body: "An error occurred while fetching products."
    
                };
    
            }
    
        };
    
     
    
        export default httpTrigger;
    
        ```
    
    Step 3: Verify `local.settings.json`
    
    Ensure that your `local.settings.json` file contains the correct connection string.
    
     
    
    ```json
    
    {
    
      "IsEncrypted": false,
    
      "Values": {
    
        "AzureWebJobsStorage": "",
    
        "FUNCTIONS_WORKER_RUNTIME": "node",
    
        "AzureWebJobsFeatureFlags": "EnableWorkerIndexing",
    
        "CONNECTION_STRING": "<YOUR-CONNECTION-STRING>"
    
      }
    
    }
    
    

    Step 4: Run and Test the Function

    1.Start the Project:

    - Press F5 in Visual Studio Code to start the Azure Functions project.
    2.Access the Endpoint:
    
    yaml
    - Open your browser and go to `http://localhost:7071/api/GetProducts`.
    

    Step 5: Debug if Necessary

     

    1. Add Logging:

        - Add logging statements to help debug any issues.

     

        ```typescript

        context.log('Query executed successfully:', items);

        ```

    1. Check Logs:

        - Use the Azure Functions logs to identify any errors or issues.

    By following these steps, you should be able to implement and test the GetProducts function correctly, ensuring it returns the expected JSON data from Cosmos DB. If you encounter any issues, the logging will help you pinpoint where things might be going wrong.

    If you are still facing the issue, please let us know in the comments. We are happy to help you.

    0 comments No comments