Integrating a REST API into a Marko.js project involves setting up the backend to handle API requests and then using those APIs in your Marko templates. Here's a step-by-step guide on how to achieve this:
1. Setup your Project
First, create a new project directory and initialize a new Node.js project if you haven't already:
mkdir marko-rest-api
cd marko-rest-api
npm init -y
2. Install Dependencies
Install the necessary packages:
npm install marko express @marko/express axios body-parser
3. Project Structure
Organize your project directory like this:
marko-rest-api/
├── src/
│ ├── components/
│ ├── pages/
│ │ ├── home/
│ │ │ ├── index.marko
│ │ │ └── index.js
│ │ ├── about/
│ │ │ ├── index.marko
│ │ │ └── index.js
│ ├── layouts/
│ │ ├── main.marko
│ ├── api/
│ │ └── data.js
│ ├── server.js
├── package.json
4. Create Page Templates
Create the main layout template in src/layouts/main.marko
:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${input.title}</title>
</head>
<body>
<header>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
</header>
<main>
<${input.body} />
</main>
</body>
</html>
Create the home page template in src/pages/home/index.marko
:
<layout-use template="../../layouts/main.marko">
<layout-put into="title">Home</layout-put>
<layout-put into="body">
<div>
<h1>Welcome to the Home Page</h1>
<ul>
$!{data.items.map(item => {
return <li>${item.name}</li>
})}
</ul>
</div>
</layout-put>
</layout-use>
5. Create Route Handlers
Create src/pages/home/index.js
for the home page route handler:
const axios = require('axios');
const template = require('./index.marko');
module.exports = async (req, res) => {
try {
const response = await axios.get('http://localhost:3000/api/data');
res.marko(template, { data: response.data });
} catch (error) {
res.status(500).send('Error fetching data');
}
};
Create src/pages/about/index.marko
and src/pages/about/index.js
similarly if needed.
6. Create a REST API
Create src/api/data.js
for the REST API:
const express = require('express');
const router = express.Router();
const data = {
items: [
{ name: 'Item 1' },
{ name: 'Item 2' },
{ name: 'Item 3' },
]
};
router.get('/data', (req, res) => {
res.json(data);
});
module.exports = router;
7. Setup the Express Server
Create src/server.js
to set up the Express server, define routes, and integrate the REST API:
const express = require('express');
const markoMiddleware = require('@marko/express').default;
const bodyParser = require('body-parser');
const homePage = require('./pages/home');
const aboutPage = require('./pages/about'); // Add if needed
const api = require('./api/data');
const app = express();
app.use(markoMiddleware());
app.use(bodyParser.json());
// Define routes
app.get('/', homePage);
app.get('/about', aboutPage); // Add if needed
// API routes
app.use('/api', api);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
8. Add Start Script
Update package.json
to add a start script:
"scripts": {
"start": "node src/server.js"
}
9. Run Your Application
Start your application by running:
npm start
Now, open your browser and navigate to http://localhost:3000
to see the home page with data fetched from the REST API.
This setup integrates a REST API with a Marko.js project using Express. You can expand this by adding more routes and APIs, handling more complex data, and incorporating more advanced features as needed. The combination of server-side rendering with Marko.js and the flexibility of Express allows you to build robust and dynamic applications.