悠悠楠杉
Ajax的初步实现(使用vscode+node.js+express框架)
06/06
- 安装 Node.js:确保你的计算机上安装了 Node.js。可以从 Node.js 官网 下载并安装。
- 安装 VSCode:如果你还没有安装 VSCode,可以访问 VSCode 官网 进行下载和安装。
- 创建 Express 应用:在 VSCode 中打开一个新的文件夹作为工作区,然后运行以下命令来初始化一个新的 Node.js 项目:
bash npm init -y npm install express
步骤 2: 创建 Express 应用
在项目根目录下创建一个名为
app.js
的文件,并写入以下代码:
```javascript
const express = require('express');
const app = express();
const port = 3000;app.use(express.json()); // 使服务器能够解析 JSON 格式的请求体
app.get('/generate-article', (req, res) => {
const { title, keywords, description } = req.query; // 从 URL 的查询参数中获取数据
const article = generateArticle(title, keywords, description);
res.send(article); // 发送生成的 Markdown 格式文章
});function generateArticle(title, keywords, description) {
return# ${title} ${keywords} ${description} [正文](#)
; // 这里用占位符 # 表示需要进一步开发正文内容生成逻辑的起点
}app.listen(port, () => {
console.log(Server is running on http://localhost:${port}
);
});
```
步骤 3: 创建前端页面以发送 Ajax 请求
- 在项目根目录下创建一个名为
index.html
的文件,并写入以下 HTML 和 JavaScript 代码:
html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Article Generator</title> </head> <body> <h1>Generate an Article</h1> <input type="text" id="title" placeholder="Enter Title"> <input type="text" id="keywords" placeholder="Enter Keywords"> <input type="text" id="description" placeholder="Enter Description"> <button onclick="generateArticle()">Generate Article</button> <pre id="article"></pre> <script> function generateArticle() { const title = document.getElementById('title').value; const keywords = document.getElementById('keywords').value; const description = document.getElementById('description').value; fetch(`http://localhost:3000/generate-article?title=${title}&keywords=${keywords}&description=${description}`) .then(response => response.text()) .then(data => { document.getElementById('article').textContent = data; }) .catch(error => console.error('Error:', error)); } </script> </body> </html>
这段 HTML 和 JavaScript 代码创建了一个简单的表单,用户可以输入标题、关键词和描述,然后点击按钮生成文章。生成的 Markdown 文章将显示在预览框中。我们使用fetch
API 向服务器发送一个 GET 请求。