nest+ webpack 代理 前端mock数据解决方案

153 阅读1分钟

webpack配置

webpack devdserve需要配置proxy,对特定请求进行转发 配置如下所示,对带有'/xiang/'的请求进行代理,代理到localhost:3000(为自己用nest启的一个express服务),配置了pathRewrite重写请求api路径

	devServer: {
		contentBase: '../browser',
		disableHostCheck: true,
		compress: true,
		hot: true,
		historyApiFallback: true,
		progress: true,
		port: '3009',
		host: '0.0.0.0',
		proxy: {
			'/xiang/': {
				target: 'http://localhost:3000/',
				pathRewrite: { '^/xiang/api/v1': '' },
				secure: false,
				changeOrigin: true,
			},
		},
	},
	optimization: {
		minimize: false,
		minimizer: [],
	},
	devtool: 'cheap-module-eval-source-map',
}

fetch设置

配置fetch实例的时候加上自定义的前缀。需要走本地mock的就使用这个带前缀的fetch就好了,可以实现自定义接口数据的Mock

const MockAPI = '/xiang'
const fetchServerInstance_ = FetchServer.configure({
	gatewayApiUrl: MockAPI,
	delayTime: API_DELAY,
	onError: (e, extra) => {
		console.log('🚀 ~ file: api.ts ~ line 123 ~ e', e)
		console.log('🚀 ~ file: api.ts ~ line 123 ~ extra', extra)
	},
})