##第八步:配置代理,解决跨域问题,方便开发环境请求数据
npm install http-proxy-middleware --save
# or
yarn add http-proxy-middleware
然后在src目录下创建 setupProxy.js 文件
// setupProxy.js
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
proxy('/api', { //api是需要转发的请求
target: 'http://localhost:5000', // 这里是接口服务器地址
changeOrigin: true
})
)
}
注意–遇到问题1:运行后报错,需要安装babel-plugin-transform-react-jsx
npm install --save-dev @babel/plugin-transform-react-jsx
执行上面代码,没有作用
解决方法:
1.删除 node_modules 文件夹
2.运行 yarn
3.重新 npm start
或
1. 进入项目根目录
2. rm -rf node_modules
3. npm install (不要使用 yarn )
yarn start
运行成功
##第九步:在运行一个React项目的时候浏览器控制台会提醒你去安装react devtools调试工具。
参考链接:https://www.cnblogs.com/liubeimeng/p/10680420.html
https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi
//安装React Devtools调试工具
git clone https://github.com/facebook/react-devtools.git
cd react-devtools
npm --registry https://registry.npm.taobao.org install
npm run build:extension:chrome
//安装成功,并且会在你的项目中生成一个新的文件夹:
//react-project ▸ react ▸ react-devtools ▸ shells ▸ chrome ▸ build
npm install -g react-devtools
##第十步:封装axios, 并配置不同环境下的域名,方便请求接口
在src下新建文件夹axios
src/axios/config.js
src/axios/httpServer.js
// src/axios/config.js
/**
* axios配置
*/
import axios from 'axios';
import { message } from 'antd';
// axios.defaults.withCredentials = true;
// 超时时间30秒
axios.defaults.timeout = 60 * 1000;
// axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// axios请求拦截器
axios.interceptors.request.use(config => {
return config;
}, error => {
message.warn(error);
return Promise.reject(error);
});
// axios响应拦截器
axios.interceptors.response.use(response => {
if (response.data) {
if (response.data.code) {
if(response.data.code === -1000 || response.data.code === -1001){
// 未登录或登录超时,跳登录
if(response.data.data && response.data.data.redirect){
window.location.href = response.data.data.redirect;
}
else if(response.data.msg){
message.warn(response.data.msg);
// 跳转到错误页面
// browserHistory.push('/404');
}
}
return response;
}
}
return response;
}, error => {
console.log(error);
return Promise.reject(error); // 返回接口返回的错误信息
});
// src/axios/httpServer.js
/**
* axios的封装 get post
*/
import axios from 'axios'
import { BASEURL } from '../assets/js/globalConstants'
import './config'
const HEADER = {'Content-Type': 'application/json;charset=UTF-8'}
const FILEHEADER = {'Content-Type': 'multipart/form-data'}
export default {
// 请求接口成功的状态值
responseOkCode: 0,
// 用户退出
getUserQuitUrl: 'account/logout',
// 用户信息
getUserInfoUrl: 'account/info',
async requestGet(url,params){
let response = await axios.get(BASEURL+url,{params:params});
if(process.env.NODE_ENV !== 'production'){
console.log('%c'+ url,'color:red',',param:',params,',response:',response.data)
}
return response.data;
},
async requestPost(url,param,timeout=60*1000*5){
try {
let response = await this.request(url,'post',param,timeout);
if(process.env.NODE_ENV !== 'production'){
console.log('%c'+ url,'color:red',',param:',param,',response:',response.data)
}
return response.data;
}catch (e) {
if(process.env.NODE_ENV !== 'production'){
console.log('%c'+ url,'color:red',',param:',param,',response:','服务器异常,请稍后重试')
}
return {code:'error',msg:'服务器异常,请稍后重试'};
}
},
async requestUpload(url,param){
try {
let response = await axios.get(BASEURL+url,'post',{param:param,headers:FILEHEADER});
if(process.env.NODE_ENV !== 'production'){
console.log('%c'+ url,'color:red',',param:',param,',response:',response.data)
}
return response.data;
}catch (e) {
if(process.env.NODE_ENV !== 'production'){
console.log('%c'+ url,'color:red',',param:',param,',response:','服务器异常,请稍后重试')
}
return {code:'error',msg:'服务器异常,请稍后重试'};
}
},
request(url,method,param,timeout,headers=HEADER){
return axios({
method:method,
url:BASEURL + url,
headers:headers,
data:param,
timeout:timeout
})
}
}
// ../assets/js/globalConstants.js
/**
* 全局常量-根据不同环境配置相应的值
*
*/
let BASEURL = '';
let BASEURL_DOMAIN = '';
const API_PREFIX = '/api/'; //api前缀
const protocol = window.location.protocol;
const DEV_DOMAIN = ''; //开发环境域名
const TEST_DOMAIN = `${protocol}//test.xx.com`; //测试环境域名
const PRE_DOMAIN = `${protocol}//pre.xx.com/`; //预发环境域名
const PRO_DOMAIN = `${protocol}//www.xx.com`; //生产环境域名
if(process.env.REACT_APP_SECRET_API === 'development'){
BASEURL_DOMAIN = DEV_DOMAIN;
}else if(process.env.REACT_APP_SECRET_API === 'test'){
BASEURL_DOMAIN = TEST_DOMAIN;
}else if(process.env.REACT_APP_SECRET_API === 'preplanned'){
BASEURL_DOMAIN = PRE_DOMAIN;
}else if(process.env.REACT_APP_SECRET_API === 'production'){
BASEURL_DOMAIN = PRO_DOMAIN;
}
BASEURL = BASEURL_DOMAIN + API_PREFIX; //请求接口地址
export { BASEURL }
// package.json 文件
{
"name": "react-new-project",
"version": "0.1.0",
"private": true,
"dependencies": {
"@babel/core": "7.6.0",
"@babel/plugin-transform-react-jsx": "^7.7.4",
"@svgr/webpack": "4.3.2",
"@typescript-eslint/eslint-plugin": "^2.2.0",
"@typescript-eslint/parser": "^2.2.0",
"antd": "^3.26.0",
"babel-eslint": "10.0.3",
"babel-jest": "^24.9.0",
"babel-loader": "8.0.6",
"babel-plugin-import": "^1.13.0",
"babel-plugin-named-asset-import": "^0.3.4",
"babel-polyfill": "^6.26.0",
"babel-preset-react-app": "^9.0.2",
"camelcase": "^5.2.0",
"case-sensitive-paths-webpack-plugin": "2.2.0",
"css-loader": "2.1.1",
"dotenv": "6.2.0",
"dotenv-expand": "5.1.0",
"eslint": "^6.1.0",
"eslint-config-react-app": "^5.0.2",
"eslint-loader": "3.0.2",
"eslint-plugin-flowtype": "3.13.0",
"eslint-plugin-import": "2.18.2",
"eslint-plugin-jsx-a11y": "6.2.3",
"eslint-plugin-react": "7.14.3",
"eslint-plugin-react-hooks": "^1.6.1",
"file-loader": "3.0.1",
"fs-extra": "7.0.1",
"html-webpack-plugin": "4.0.0-beta.5",
"http-proxy-middleware": "^0.20.0",
"identity-obj-proxy": "3.0.0",
"is-wsl": "^1.1.0",
"jest": "24.9.0",
"jest-environment-jsdom-fourteen": "0.1.0",
"jest-resolve": "24.9.0",
"jest-watch-typeahead": "0.4.0",
"mini-css-extract-plugin": "0.8.0",
"optimize-css-assets-webpack-plugin": "5.0.3",
"pnp-webpack-plugin": "1.5.0",
"postcss-flexbugs-fixes": "4.1.0",
"postcss-loader": "3.0.0",
"postcss-normalize": "7.0.1",
"postcss-preset-env": "6.7.0",
"postcss-safe-parser": "4.0.1",
"react": "^16.12.0",
"react-app-polyfill": "^1.0.4",
"react-dev-utils": "^9.1.0",
"react-dom": "^16.12.0",
"resolve": "1.12.0",
"resolve-url-loader": "3.1.0",
"semver": "6.3.0",
"style-loader": "1.0.0",
"terser-webpack-plugin": "1.4.1",
"ts-pnp": "1.1.4",
"url-loader": "2.1.0",
"webpack": "4.41.0",
"webpack-dev-server": "3.2.1",
"webpack-manifest-plugin": "2.1.1",
"workbox-webpack-plugin": "4.3.1"
},
"scripts": {
"start": "cross-env REACT_APP_SECRET_API=development node scripts/start.js",
"testbuild": "cross-env REACT_APP_SECRET_API=test node scripts/build.js",
"prebuild": "cross-env REACT_APP_SECRET_API=preplanned node scripts/build.js",
"build": "cross-env REACT_APP_SECRET_API=production node scripts/build.js"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"jest": {
"roots": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"
],
"setupFiles": [
"react-app-polyfill/jsdom"
],
"setupFilesAfterEnv": [],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
],
"testEnvironment": "jest-environment-jsdom-fourteen",
"transform": {
"^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$",
"^.+\\.module\\.(css|sass|scss)$"
],
"modulePaths": [],
"moduleNameMapper": {
"^react-native$": "react-native-web",
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"web.js",
"js",
"web.ts",
"ts",
"web.tsx",
"tsx",
"json",
"web.jsx",
"jsx",
"node"
],
"watchPlugins": [
"jest-watch-typeahead/filename",
"jest-watch-typeahead/testname"
]
},
"babel": {
"presets": [
"react-app"
]
},
"devDependencies": {
"babel-plugin-transform-react-jsx": "^6.24.1",
"cross-env": "^6.0.3",
"node-sass": "^4.13.0",
"sass-loader": "^7.2.0"
}
}
修改README.md文件
# 项目技术栈:
## react + react-redux + react-router + typeScript + axios + es6
## 安装
### `npm install`
## 运行
### `npm run start` or
### `yarn start`
## 测试环境打包
### `npm run testbuild`
## 预发环境打包
### `npm run prebuild`
## 生产环境打包
### `npm run build`
注意:
先备份一份项目,不需要typeScript,再继续配置
未完,继续下一篇
【第一部分】create-react-app 技术栈:react+react-router+redux+axios+es6+webpack
【第二部分】create-react-app 技术栈:react+react-router+redux+axios+es6+webpack
【第三部分】create-react-app 技术栈:react+react-router+redux+axios+es6+webpack