Step 1: Setting Up the Project
- Create a project directory:
mkdir simple-forum cd simple-forum
- Initialize a Node.js project:bashCopy code
npm init -y
- Install necessary packages:
npm install express body-parser cors
Step 2: Backend Code (Node.js with Express)
Create a file named server.js
in your project directory:
javascriptCopy codeconst express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(bodyParser.json());
let posts = [];
// Get all posts
app.get('/api/posts', (req, res) => {
res.json(posts);
});
// Create a new post
app.post('/api/posts', (req, res) => {
const { title, content } = req.body;
const newPost = { id: posts.length + 1, title, content };
posts.push(newPost);
res.status(201).json(newPost);
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 3: Frontend Code (HTML, CSS, and JavaScript)
Create an index.html
file in the project directory:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Forum</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
text-align: center;
}
#postForm {
margin-bottom: 20px;
}
.post {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<h1>Simple Forum</h1>
<div id="postForm">
<input type="text" id="title" placeholder="Post Title" required>
<textarea id="content" placeholder="Post Content" required></textarea>
<button onclick="submitPost()">Submit</button>
</div>
<div id="posts"></div>
<script>
async function fetchPosts() {
const response = await fetch('http://localhost:3000/api/posts');
const posts = await response.json();
displayPosts(posts);
}
function displayPosts(posts) {
const postsDiv = document.getElementById('posts');
postsDiv.innerHTML = '';
posts.forEach(post => {
const postDiv = document.createElement('div');
postDiv.classList.add('post');
postDiv.innerHTML = `<h3>${post.title}</h3><p>${post.content}</p>`;
postsDiv.appendChild(postDiv);
});
}
async function submitPost() {
const title = document.getElementById('title').value;
const content = document.getElementById('content').value;
const response = await fetch('http://localhost:3000/api/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ title, content })
});
if (response.ok) {
document.getElementById('title').value = '';
document.getElementById('content').value = '';
fetchPosts();
}
}
fetchPosts();
</script>
</body>
</html>
Step 4: Running the Application
- Start the backend server:
node server.js
- Open
index.html
in your web browser.
Leave a Reply