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;
}
}