Commit 3157c448 authored by 张烨's avatar 张烨

feat: local env config and proxy settings

parent 87f5e91a
PROXY=localhost:10087
HOST=localhost
PORT=3001
\ No newline at end of file
...@@ -10,4 +10,5 @@ npm-debug.log ...@@ -10,4 +10,5 @@ npm-debug.log
.idea .idea
src/umi src/umi
src/.umi src/.umi
*.local
...@@ -216,6 +216,7 @@ ...@@ -216,6 +216,7 @@
"webpack-hot-middleware": "2.24.3", "webpack-hot-middleware": "2.24.3",
"webpack-pwa-manifest": "4.0.0", "webpack-pwa-manifest": "4.0.0",
"whatwg-fetch": "3.0.0", "whatwg-fetch": "3.0.0",
"yorkie": "^2.0.0" "yorkie": "^2.0.0",
"express-http-proxy": "^1.6.2"
} }
} }
const fs = require('fs');
const { resolve } = require('path');
const isDev = process.env.NODE_ENV !== 'production';
const parse = src => {
const obj = {};
// convert Buffers before splitting into lines and processing
src
.toString()
.split('\n')
.forEach(line => {
// matching "KEY' and 'VAL' in 'KEY=VAL'
const keyValueArr = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/);
// matched?
if (keyValueArr != null) {
const key = keyValueArr[1];
// default undefined or missing values to empty string
let value = keyValueArr[2] || '';
// expand newlines in quoted values
const len = value ? value.length : 0;
if (
len > 0 &&
value.charAt(0) === '"' &&
value.charAt(len - 1) === '"'
) {
value = value.replace(/\\n/gm, '\n');
}
// remove any surrounding quotes and extra spaces
value = value.replace(/(^['"]|['"]$)/g, '').trim();
obj[key] = value;
}
});
return obj;
};
const dotenvPath = [
resolve(process.cwd(), '.env'),
isDev && resolve(process.cwd(), '.env.local'),
].filter(Boolean);
const env = dotenvPath
.filter(path => fs.existsSync(path))
.map(path => parse(fs.readFileSync(path)))
.reduce((envObj, parsed) => Object.assign(envObj, parsed), {});
// eslint-disable-next-line array-callback-return
Object.keys(env).map(key => {
// eslint-disable-next-line no-prototype-builtins
if (!process.env.hasOwnProperty(key)) process.env[key] = env[key];
});
/* eslint consistent-return:0 import/order:0 */ /* eslint consistent-return:0 import/order:0 */
// 先挂环境变量
require('./env');
const express = require('express'); const express = require('express');
const logger = require('./logger'); const logger = require('./logger');
...@@ -26,7 +27,7 @@ setup(app, { ...@@ -26,7 +27,7 @@ setup(app, {
// get the intended host and port number, use localhost and port 3000 if not provided // get the intended host and port number, use localhost and port 3000 if not provided
const customHost = argv.host || process.env.HOST; const customHost = argv.host || process.env.HOST;
const host = customHost || null; // Let http.Server use its default IPv6/4 host const host = customHost || null; // Let http.Server use its default IPv6/4 host
const prettyHost = customHost || 'localhost'; const prettyHost = (host !== 'origin' && customHost) || 'localhost';
// use the gzipped bundle // use the gzipped bundle
app.get('*.js', (req, res, next) => { app.get('*.js', (req, res, next) => {
......
...@@ -2,7 +2,12 @@ const path = require('path'); ...@@ -2,7 +2,12 @@ const path = require('path');
const webpack = require('webpack'); const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware'); const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware');
const proxy = require('express-http-proxy'); const {
createProxyMiddleware,
Filter,
Options,
RequestHandler,
} = require('http-proxy-middleware');
function createWebpackMiddleware(compiler, publicPath) { function createWebpackMiddleware(compiler, publicPath) {
return webpackDevMiddleware(compiler, { return webpackDevMiddleware(compiler, {
...@@ -26,7 +31,7 @@ module.exports = function addDevMiddlewares(app, webpackConfig) { ...@@ -26,7 +31,7 @@ module.exports = function addDevMiddlewares(app, webpackConfig) {
// Since webpackDevMiddleware uses memory-fs internally to store build // Since webpackDevMiddleware uses memory-fs internally to store build
// artifacts, we use it instead // artifacts, we use it instead
const fs = middleware.fileSystem; const fs = middleware.fileSystem;
let proxyHost = 'localhost:3002'; let proxyHost = process.env.PROXY;
app.get('/setproxy', (req, res) => { app.get('/setproxy', (req, res) => {
if (req.query && req.query.host) { if (req.query && req.query.host) {
proxyHost = req.query.host; proxyHost = req.query.host;
...@@ -35,30 +40,18 @@ module.exports = function addDevMiddlewares(app, webpackConfig) { ...@@ -35,30 +40,18 @@ module.exports = function addDevMiddlewares(app, webpackConfig) {
res.send(400); res.send(400);
} }
}); });
app.use(
'/proxy/*', if (
proxy(() => proxyHost, { proxyHost &&
proxyReqPathResolver: req => { (proxyHost.toLowerCase() !== 'origin' ||
const parts = req.originalUrl.split('?'); proxyHost.toLowerCase() !== 'off' ||
const queryString = parts[1]; proxyHost !== '0')
const updatedPath = parts[0].replace(/\/proxy\//, '/'); ) {
return updatedPath + (queryString ? `?${queryString}` : ''); app.use(
}, process.env.PROXY_PREFIX || '/Cityinterface',
proxyReqOptDecorator: proxyReqOpts => { createProxyMiddleware({ target: proxyHost, changeOrigin: true }),
// you can update headers );
proxyReqOpts.headers.origin = proxyHost; }
// proxyReqOpts.headers.Accept = '*/*';
// proxyReqOpts.headers['cookie'] =
// 'UM_distinctid=17543f1ba9ea0a-05f0523c41099d-c781f38-1fa400-17543f1ba9f59; CNZZDATA1278602214=833011536-1603161215-%7C1603161215';
// proxyReqOpts.headers['Accept-Encoding'] = 'gzip, deflate, br';
// proxyReqOpts.headers['Accept-Language'] =
// 'zh-CN,zh;q=0.9,zh-TW;q=0.8,en-US;q=0.7,en;q=0.6';
// console.log({ proxyReqOpts });
// you can change the method
return proxyReqOpts;
},
}),
);
app.get('*', (req, res) => { app.get('*', (req, res) => {
fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => { fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => {
......
// /* eslint-disable*/ /* eslint-disable*/
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Form, Input, Button, Space, Select } from 'antd'; import { Form, Input, Button, Space, Select } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'; import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
...@@ -28,10 +28,10 @@ const RequestTest = () => { ...@@ -28,10 +28,10 @@ const RequestTest = () => {
console.error(err); console.error(err);
}); });
} else { } else {
get('/setproxy', { host: url.match(/^https?:\/\/([^\/]+)/)[1] }).then( get('/setproxy', { host: url.match(/^(https?:\/\/[^\/]+)/)[1] }).then(
res => { res => {
const proxyUrl = url.replace(/^https?:\/\/([^\/]+)/, $1 => { const proxyUrl = url.replace(/^https?:\/\/([^\/]+)/, $1 => {
return `${window.location.origin}/proxy`; return `${window.location.origin}`;
}); });
methodMap[method](proxyUrl, params) methodMap[method](proxyUrl, params)
.catch(err => { .catch(err => {
......
...@@ -3,19 +3,19 @@ import { request } from '../utils/request'; ...@@ -3,19 +3,19 @@ import { request } from '../utils/request';
const axios = request.defaults; const axios = request.defaults;
const get = async (url, params, options = {}) => const get = async (url, params, options = {}) =>
request({ request({
url, url,
method: 'get', method: 'get',
params, params,
...options, ...options,
}); });
const post = async (url, params, options = {}) => const post = async (url, params, options = {}) =>
request({ request({
url, url,
params, params,
method: 'post', method: 'post',
...options, ...options,
}); });
export { get, post } export { get, post };
// import {get, post} from '../index'
// export const getUserInfo = param => {
// return get('/cityinterface/getUserinfo', param)
// }
...@@ -25,8 +25,6 @@ const getMatchedConfig = requestConfig => { ...@@ -25,8 +25,6 @@ const getMatchedConfig = requestConfig => {
} }
}; };
axios.defaults.baseURL = window.location.origin;
export const request = (config, ctx) => { export const request = (config, ctx) => {
const { const {
url, url,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment