- Python (使用Flask作为后端框架)aladingroup.cn
Flask后端示例:
python
from flask import Flask, request, jsonify
app = Flask(name)
假设这是游戏商品的数据库(实际应用中应使用数据库)
games = [
{“id”: 1, “name”: “Game 1”, “price”: 9.99},
{“id”: 2, “name”: “Game 2”, “price”: 19.99},
]
@app.route(‘/games’, methods=[‘GET’])
def get_games():
return jsonify(games)
@app.route(‘/games/int:game_id’, methods=[‘GET’])
def get_game(game_id):
for game in games:
if game[‘id’] == game_id:
return jsonify(game)
return jsonify({‘error’: ‘Game not found’}), 404
… 其他路由,如购买游戏等
if name == ‘main’:
app.run(debug=True)
2. JavaScript (使用Node.js和Express作为后端框架)
Express后端示例:
javascript
const express = require(‘express’);
const app = express();
const port = 3000;
// 假设这是游戏商品的数据库(实际应用中应使用数据库)
const games = [
{ id: 1, name: ‘Game 1’, price: 9.99 },
{ id: 2, name: ‘Game 2’, price: 19.99 },
];
app.get(‘/games’, (req, res) => {
res.json(games);
});
app.get(‘/games/:gameId’, (req, res) => {
const gameId = parseInt(req.params.gameId);
const game = games.find(game => game.id === gameId);
if (game) {
res.json(game);
} else {
res.status(404).json({ error: ‘Game not found’ });
}
});
// … 其他路由,如购买游戏等
app.listen(port, () => {
console.log(Server is running on port ${port}
);
});
3. 前端示例 (使用HTML/CSS/JavaScript)
由于前端代码通常与具体的UI设计和交互逻辑相关,这里只提供一个简单的HTML结构和一个JavaScript函数来调用后端API的示例。
HTML和JavaScript示例:
html
- Python (使用Flask作为后端框架)
Flask后端示例:
python
from flask import Flask, request, jsonify
app = Flask(name)
假设这是游戏商品的数据库(实际应用中应使用数据库)
games = [
{“id”: 1, “name”: “Game 1”, “price”: 9.99},
{“id”: 2, “name”: “Game 2”, “price”: 19.99},
]
@app.route(‘/games’, methods=[‘GET’])
def get_games():
return jsonify(games)
@app.route(‘/games/int:game_id’, methods=[‘GET’])
def get_game(game_id):
for game in games:
if game[‘id’] == game_id:
return jsonify(game)
return jsonify({‘error’: ‘Game not found’}), 404
… 其他路由,如购买游戏等
if name == ‘main’:
app.run(debug=True)
2. JavaScript (使用Node.js和Express作为后端框架)
Express后端示例:
javascript
const express = require(‘express’);
const app = express();
const port = 3000;
// 假设这是游戏商品的数据库(实际应用中应使用数据库)
const games = [
{ id: 1, name: ‘Game 1’, price: 9.99 },
{ id: 2, name: ‘Game 2’, price: 19.99 },
];
app.get(‘/games’, (req, res) => {
res.json(games);
});
app.get(‘/games/:gameId’, (req, res) => {
const gameId = parseInt(req.params.gameId);
const game = games.find(game => game.id === gameId);
if (game) {
res.json(game);
} else {
res.status(404).json({ error: ‘Game not found’ });
}
});
// … 其他路由,如购买游戏等
app.listen(port, () => {
console.log(Server is running on port ${port}
);
});
3. 前端示例 (使用HTML/CSS/JavaScript)
由于前端代码通常与具体的UI设计和交互逻辑相关,这里只提供一个简单的HTML结构和一个JavaScript函数来调用后端API的示例。
HTML和JavaScript示例:
html