最近在整理自己的项目时,想把本地的一个 Vue CLI 项目推送到 GitHub 上进行版本管理。本以为是个简单操作,结果一路踩了几个典型的“新手坑”。今天就来记录一下整个过程,希望能帮到和我一样刚接触 Git 和 GitHub 的朋友。

第一步:常规提交却报错 —— 没有配置远程仓库

我一开始的操作非常“朴素”:

git add .
git commit -m 'init project'
git push

结果控制台直接报错:

fatal: No configured push destination.
Either specify the URL from the command-line or configure a remote repository using     
    git remote add <name> <url>
and then push using the remote name
    git push <name>

原因分析
这个错误的意思是——Git 不知道你要把代码推送到哪里。因为你还没有为本地仓库配置任何远程仓库地址(remote)。这就像你想寄快递,但没填收件地址一样。

解决方法
需要先在 GitHub 上新建一个空仓库(注意不要勾选 “Initialize this repository with a README”,否则后续可能需要处理冲突),然后在本地执行:

git remote add origin https://github.com/xuehao1997/vue-cli.git

验证是否添加成功:

git remote -v

输出如下说明配置成功:

origin  https://github.com/xuehao1997/vue-cli.git (fetch)
origin  https://github.com/xuehao1997/vue-cli.git (push)

看起来一切正常,于是继续推送:

git push -u origin master

第二步:认证失败 —— GitHub 已禁用密码登录

然而,又报错了:

remote: Invalid username or token. Password authentication is not supported for Git operations.
fatal: Authentication failed for 'https://github.com/xuehao1997/vue-cli.git/'

原因分析
2021 年 8 月起,GitHub 正式停止支持使用账号密码进行 Git 操作的认证方式。这意味着即使你输入正确的用户名和密码,也会被拒绝。现在必须使用以下两种方式之一:

  • Personal Access Token (PAT)(基于 HTTPS)
  • SSH 密钥(基于 SSH 协议,更安全且无需每次输入凭证)

我决定采用更推荐的 SSH 方式

第三步:配置 SSH 密钥

1. 生成 SSH 密钥

在终端执行:

ssh-keygen -t rsa -b 4096 -C "743195023@qq.com"

按回车使用默认路径(~/.ssh/id_rsa),也可以设置密码(passphrase)增强安全性(可选)。

2. 查看公钥内容

cat ~/.ssh/id_rsa.pub

你会看到类似这样的字符串:

ssh-rsa AAAAB3NzaC1yc2E... 743195023@qq.com

3. 将公钥添加到 GitHub

  • 打开 GitHub Settings
  • 进入 SSH and GPG keys
  • 点击 New SSH key
  • Title 随便填(比如 “My MacBook”)
  • id_rsa.pub 的全部内容粘贴进去,点击 Add SSH key

4. 测试 SSH 连接

ssh -T git@github.com

如果看到:

Hi xuehao1997! You've successfully authenticated, but GitHub does not provide shell access.

恭喜!SSH 认证成功 ✅

第四步:推送代码(关键细节)

把远程地址从 HTTPS 改成 SSH:

git remote set-url origin git@github.com:xuehao1997/vue-cli.git

再检查一下:

git remote -v
# 应该显示:
# origin  git@github.com:xuehao1997/vue-cli.git (fetch)
# origin  git@github.com:xuehao1997/vue-cli.git (push)

最终推送

git push -u origin master

✅ 成功!代码顺利上传到 GitHub。


总结:踩坑清单 & 最佳实践

问题 原因 解决方案
No configured push destination 未设置远程仓库 git remote add origin <url>
Password authentication is not supported GitHub 禁用密码认证 改用 SSH 或 PAT
推送失败/认证失败 未配置 SSH 或 Token 生成 SSH 密钥并添加到 GitHub
地址混乱 混用 HTTPS 和 SSH 统一使用 SSH 地址

建议

  • 新项目一律使用 SSH 方式管理远程仓库,一劳永逸。
  • 定期备份 SSH 私钥(id_rsa 文件),但切勿泄露
  • 如果团队协作,确保每个成员都配置好自己的 SSH。

希望这篇记录能帮你少走弯路。Git 虽然强大,但初学者很容易在“连接远程仓库”这一步卡住。只要理解背后的原理(认证机制 + 远程地址配置),就能从容应对。

🌟 小贴士:如果你还在用 master 分支,注意 GitHub 默认分支现在是 main。可以考虑统一使用 main 避免未来兼容问题。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐