大前端快闪二:react开发模式 一键启动多个服务

最近全权负责了一个前后端分离的web项目,前端使用create-react-app[1], 后端使用golang做的api服务。
npx create-react-app my-app
cd my-app
npm start
歘歘歘,就搭建了一个react前端项目。
前端老鸟都知道npm start或yarn start以开发模式启动react App:在localhost:3000调试预览前端项目,编辑器的变更会实时体现在web页面。
前端老鸟也知道npm run build或yarn build是以生产为目标,将优化后的静态文件输出到build文件夹 (优化构建性能、压缩产出物、给文件名哈希)。
从一个全栈程序员的视角,开发时最好能一次启动前后端两个程序
。

快闪二:你能在react app开发模式中一键启动多个服务吗?

1. 安装concurrently插件
npm install concurrently -D
2 . 配置npm命令
"scripts": {
"start": "concurrently \"react-scripts start\" \"go run main.go\" ",
"build": "react-app-scripts build",
"test": "react-app-scripts test",
"eject": "react-scripts eject"
},
注意上面的start脚本内容: react-scripts start启动了前端app, go run main.go启动了后端api服务。
3. npm start或yarn start启动项目
开发模式,前后端项目不在一个端口,内置axios发起的ajax请求存在跨域。
解决跨域问题,要么反向代理,要么让后端做CORS。
这里我们采用反向代理的方式。
4. react开发模式设置proxy[2]
create-react-app允许你设置一个proxy,仅用于开发模式。
To tell the development server to proxy any unknown requests to your API server in development, add a
proxyfield to your package.json。
在package.json文件,设置要代理的后端地址 proxy:"localhost:8034"
,开发模式localhost:3000收到的未知请求将会由前端开发服务器代理转发。
引用链接
[1] create-react-app: https://github.com/facebook/create-react-app[2] react开发模式设置proxy: https://coursework.vschool.io/setting-up-a-full-stack-react-application/
性感豹纹
鹅厂二面,Nginx回忆录
前端镜像打包这么慢,你该反省一下dockerfile的姿势了




本文内容和制图均为原创,文章永久更新地址请参阅左下角原文,老鸟轻喷,菜鸟互啄。
