Skip to content

Commit

Permalink
fix: parse body of fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
yunsii committed Apr 10, 2021
1 parent 4dc6528 commit dad8f24
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 2 deletions.
31 changes: 31 additions & 0 deletions example/src/pages/Welcome/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,36 @@ export default function Welcome() {
});
};

const helloPost = () => {
setData(undefined);
setError(undefined);
setLoading(true);
fetch('/api/hello', {
method: 'post',
body: JSON.stringify({
hello: 'world',
}),
})
.then((response) => {
response
.clone()
.text()
.then((text) => console.log('hello text:\n', text));
return response.json();
})
.then((json) => {
console.log('data', json);
setData(json);
})
.catch((err) => {
console.log('error', err);
setError(err);
})
.finally(() => {
setLoading(false);
});
};

const version = () => {
setData(undefined);
setError(undefined);
Expand Down Expand Up @@ -72,6 +102,7 @@ export default function Welcome() {
<br />
<br />
<Button onClick={hello}>mock: hello</Button>
<Button onClick={helloPost}>mock: hello post</Button>
<Button onClick={version}>mock: version</Button>
<div style={{ width: '100%', minHeight: 100 }}>
{loading && <div>{'loading...'}</div>}
Expand Down
2 changes: 1 addition & 1 deletion example/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { defineConfig } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
import tsconfigPaths from 'vite-tsconfig-paths';

import vitApp from '../packages/vite-plugin';
import vitApp from '../packages/vite-plugin/dist';
import routes from './config/routes';

// https://vitejs.dev/config/
Expand Down
11 changes: 10 additions & 1 deletion packages/vite-plugin/src/generateFiles/mockFetch.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ function qs(url) {
);
}

function loadBody(fetchBody: any) {
try {
return JSON.parse(fetchBody);
} catch(error) {
console.log("loadBody error", error);
return fetchBody;
}
}

export default function mockFetch() {
if (!Mock || !Mock.mock) {
throw new Error('Mock.js is required.');
Expand Down Expand Up @@ -53,7 +62,7 @@ export default function mockFetch() {
? // 保持与 mock 定义一致的入参
item.template.call(this, {
query: qs(url),
body: options?.body,
body: loadBody(options?.body),
headers: options?.headers,
})
: Mock.mock(item.template);
Expand Down

0 comments on commit dad8f24

Please sign in to comment.