小白也能懂科技小手工制作一口气解读ChatGPT编程超能力的13个章节50个实例
前言在这个科技小手工制作的旅程中,我们将通过十三个章节,带你探索ChatGPT在编程开发领域的无限可能。从代码生成到数据库查询,每一步都可以帮助我们提高效率,降低错误率,让我们的编程工作更加高效。
不过,也要记得,虽然ChatGPT是一个强大的工具,但它并不能完全替代我们的知识和技能。我们需要使用它提供的便利,同时也要不断学习,不断提升自己的技能。
一、代码生成
1.1 提示词:
Generate a semantic and accessible HTML and (framework) CSS [UI component] consisting of [component parts]. The [component parts] should be [layout].
举例:
Generate a semantic HTML and Tailwind CSS Contact Support form consisting of the users name, email, issue type, and message. The form elements should be stacked vertically and placed inside a card.
生成结果:下面是一个使用语义化HTML和Tailwind CSS构建的“联系支持”表单,包含用户的姓名、电子邮件、问题类型和留言。表单元素垂直堆叠,放置在一个卡片中。
<form class="card">
<h2>联系支持</h2>
<div>
<label for="name">名字:</label>
<input type="text" id="name" required />
</div>
<div>
<label for="email">邮箱:</label>
<input type="email" id="email" required />
</div>
<!-- 其他字段 -->
</form>
1.2 提示词:
Write a JavaScript function. It accepts [input] and returns [output].
举例:
Write a JavaScript function that accepts an array of numbers as input and returns the sum of all even numbers in the array.
生成结果:以下是接受数组作为输入并返回该数组所有偶数之和的JavaScript函数:
function getSumOfEvenNumbers(arr) {
let sum = ; // 初始化和为0
for (let i = ; i < arr.length; i++) {
if (arr[i] % === ) { // 如果当前数字是偶数,则加到总和上
sum += arr[i]; } }
return sum;
}
例如,如果输入的是[4,6,8],那么该函数将返回16(即4+6+8)。
1.3 提示词:
Write an/ an API using to fetch data from.
Example:
Write an Express.js API to fetch user data from MongoDB.
Generated result:
Here is an example Express.js API using MongoDB to fetch user data:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Connect to MongoDB database
mongoose.connect(
'mongodb://localhost/myapp',
{ useNewUrlParser: true },
);
// Create User model schema
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
});
const User = mongoose.model(User, userSchema);
// Define route handlers
app.get('/api/users', async (req, res) => {
try {
const usersData = await User.find();
res.status(200).json(usersData);
} catch (error) {
console.error(error.message);
res.status(500).send(error.message);
}
});
// Start server on port :3000
server.listen(portNumber || portName)
.on('listening', () => console.log(Server running on port ${port}))
.on('error', error => console.error(Error starting server, error));
This code defines two routes for fetching all users' information or specific users by their IDs.
/api/users: Fetches all users' information.
/api/user/:id: Fetches specific user's information based on their ID.
The getUsers route uses User.find() method with callback function which calls res.json() when it retrieves all records successfully.
The second route checks if the specified ID exists before calling res.json().