krouzek:expressjs

Toto je starší verze dokumentu!


Write a step-by-step tutorial how to create an ExpressJS application with two example routes, GET and POST interacting via JSON. Make that a POST game/ to create new game and GET game/:id to query the game state.

Sure, here's the step-by-step tutorial for creating an Express.js application with GET and POST routes in DokuWiki syntax:

  • Node.js installed on your system.
  • A basic understanding of JavaScript and HTTP concepts.

Create a new directory for your project and navigate to it in your terminal.

Initialize a new Node.js project by running the following command:

npm init

Follow the prompts to configure your project.

Install the Express.js framework:

npm install express --save

Create a new JavaScript file (e.g., app.js) in your project directory.

Open app.js in your code editor and import Express:

const express = require('express');
const app = express();
const port = 3000; // You can choose any port you prefer

Create a simple in-memory storage for game data. In a real application, you'd use a database.

const games = {};
let gameIdCounter = 1;

Create a POST route to create a new game. This route will accept JSON data and generate a unique game ID.

app.use(express.json());
 
app.post('/game', (req, res) => {
const newGameId = gameIdCounter++;
const newGame = {
id: newGameId,
state: 'New', // You can initialize the state as needed
};
games[newGameId] = newGame;
res.status(201).json(newGame);
});

Create a GET route to query the game state by ID.

app.get('/game/:id', (req, res) => {
const gameId = parseInt(req.params.id);
const game = games[gameId];
if (game) {
res.json(game);
} else {
res.status(404).json({ error: 'Game not found' });
}
});

Add the following code at the end of your app.js to start the server:

app.listen(port, () => {
echo "Server is running on port ${port}";
});

In your terminal, navigate to your project directory and run your Express application:

node app.js

Your Express app should now be running on the specified port (in this case, port 3000).

You can test your routes using tools like Postman, cURL, or by creating a simple front-end application.

That's it! You've created an Express.js application with two example routes (GET and POST) that interact via JSON to manage a simple game state. You can expand upon this foundation to build more complex applications with Express.js.

  • krouzek/expressjs.1698785955.txt.gz
  • Poslední úprava: 2023/11/15 20:54
  • (upraveno mimo DokuWiki)