0

I'm trying to create web app using open-source LWC and node.js and following the steps mentioned in this blog. My app is working till Step 2. I'm stuck in Step 3 where I need to Create a GET method at server-side which provides a list of students.

In the blog it's mentioned /src/server/index.js is the entry point for the server, instead I have /src/server/api.js, which I believe should also work.

I'm not getting any data on click on get student button.

api.js:

// Simple Express server setup to serve for local testing/dev API server
const compression = require('compression');
const helmet = require('helmet');
const express = require('express');

const app = express();
app.use(helmet());
app.use(compression());

const HOST = process.env.API_HOST || 'localhost';
const PORT = process.env.API_PORT || 3002;

app.get('/api/v1/endpoint', (req, res) => {
    res.json({ success: true });
});

app.listen(PORT, () =>
    console.log(
        `✅  API Server started: http://${HOST}:${PORT}/api/v1/endpoint`
    )
);

module.exports = app => {
    // put your express app logic here
    app.get('/students', (req, res) => {
        // preparing array of student
        var students = [
            {
                name: 'James Smith',
                age: 17,
                id: 1
            },
            {
                name: 'Elizabeth Johnson',
                age: 17,
                id: 2
            },
            {
                name: 'David Wilson',
                age: 17,
                id: 3
            },
        ];
        //next line will send response in JSON format
        res.json(students);
    });
};

students.html:

<template>
    
    <div>
        <button onclick={getStudents}>Get Students</button>
    </div>
    <!-- Check if data is available -->
    <template if:true={isStudentsAvailable}>
        <div>
            <h2>Students Data:</h2>
            <table>
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>Name</th>
                        <th>Age</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- iterating through for each -->
                    <template for:each={students} for:item="student">
                        <!-- unique key is required for for:each -->
                        <tr key={student.id}>
                            <!-- rendering data -->
                            <td>{student.id}</td>
                            <td>{student.name}</td>
                            <td>{student.age}</td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
    </template>
</template>

students.js:

import { LightningElement, track } from 'lwc';


export default class Students extends LightningElement {
    @track students = [];

    /*
    getStudents(){
        //assigning students data to students variable
        this.students = [
            {
                name: 'James Smith',
                age: 17,
                id: 1
            },
            {
                name: 'Elizabeth Johnson',
                age: 17,
                id: 2
            },
            {
                name: 'David Wilson',
                age: 19,
                id: 3
            },
        ];
    }
    */

    getStudents(){
        //using javascrip native fetch method to get data from server
        fetch('/students').then(res => {
            res.json().then(data =>{
                this.students = data;
                console.log(data);
            });
        }).catch(err => {
            console.error(err);
        });
    }

    //getter method to check if students array have value
    get isStudentsAvailable(){
        return this.students.length > 0;
    }
}
2
  • did you change your entry point in package.json file?
    – sdandamud1
    Apr 12, 2022 at 16:32
  • what changes do I need to make in my entry point in package.json? I have not seen any steps related to that. Apr 12, 2022 at 22:01

1 Answer 1

2

LWC Services has been deprecated. On a personal note, since the deprecation I've had shitty luck getting anything to work with it. It's better to switch to LWR.

The bad news is that LWR is terribly documented as of this post. Good news is that I just managed to push out a demo I've been working on that is setup with LWR/Express and Client-Side Routing:

https://github.com/jonshipman/lwr-demo

Just clone it, yarn install then yarn start. Due to LWR dependencies it does require node-gyp.

Effectively I'm using LWR inside node as a proxy under express. You could skip this process and use the LWR binary, however, I like the flexibility of having it scripted so I can perform special tasks pre and post startup. Setup as a secondary process as LWR will hot reload and I like to keep express separate from that. Uses http-proxy-middleware for the proxy.

You'll need to put your app.get calls before the wildcard for the proxy.

3
  • Where is the index.html? I don't see it when a new lwc project is created. Also, I am not able to understand how is being served. Jul 13, 2022 at 7:19
  • 1
    src/layouts/index.html It is being served via LWR and an express proxy. You can drop the express proxy, but most projects I write has a server component so you'd put those routes in server-web.js.
    – JonShipman
    Jul 14, 2022 at 13:06
  • That makes sense, thanks! Jul 14, 2022 at 13:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .