同一GitHub仓库存放Spring与React项目推送报错解决方法
问题原因
推送被拒、强推覆盖代码的核心原因是:React、Spring两个项目各自独立初始化了Git仓库,且都往远程仓库的同一个master分支推送。两个本地仓库的提交历史完全独立没有交集,Git检测到远程分支存在本地缺失的提交时就会拦截推送;如果加--force强推,会直接用当前本地的提交历史替换远程所有内容,之前上传的项目自然会被删掉。
对应报错信息如下:
bar1s@DESKTOP-C8L726O MINGW64 ~/Desktop/spring/auction-project (master) $ git push -u origin master To https://github.com/cevikbaris/Auction-Website.git ! [rejected] master -> master (fetch first) error: failed to push some refs to 'https://github.com/cevikbaris/Auction-Website.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details.
解决步骤
采用同仓库分目录存放前后端的规范方案即可,操作流程如下:
- 本地新建一个空文件夹作为仓库根目录,打开Git Bash执行初始化和远程绑定
git init git remote add origin https://github.com/cevikbaris/Auction-Website.git
- 拉取远程仓库已经上传的第一个项目的代码
git pull origin master
- 在仓库根目录下新建两个子文件夹,通常命名为
frontend(存放React前端代码)和backend(存放Spring后端代码) - 整理文件:
- 把刚拉下来的第一个项目的所有文件,移动到对应的子文件夹中
- 把本地另一个未推送成功的项目的所有文件,复制到剩下的子文件夹中
- 重点:一定要删除两个子文件夹内自带的
.git隐藏文件夹,避免形成嵌套子仓库导致后续提交异常
- 提交变更并推送到远程
git add . git commit -m "调整目录结构,分前后端目录存放React、Spring项目代码" git push origin master
注意事项
- 非必要场景不要使用
git push --force强制推送,该操作会直接覆盖远程分支的提交历史,极易造成代码丢失 - 后续开发时,所有代码变更都在这个整合后的根仓库里执行add、commit、push操作即可,不需要再单独给前后端项目初始化独立Git仓库
内容的提问来源于stack exchange,提问作者Baris
相关产品推荐
相关产品推荐

