Skip to content

Commit 4004c96

Browse files
author
yang.zhang
committed
fetch cookie
1 parent 87fc70a commit 4004c96

File tree

7 files changed

+200
-81
lines changed

7 files changed

+200
-81
lines changed

.config.js

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
/* 项目配置文件 */
2+
3+
module.exports = {
4+
devServer: 'http://localhost:3000',
5+
proServer: 'http://localhost:3000',
6+
token: 'X-BLACKCAT-TOKEN',
7+
};

package.json

+3-1
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,14 @@
1111
"e2e:open": "vue-cli-service e2e:open"
1212
},
1313
"dependencies": {
14+
"promise-polyfill": "^7.1.0",
1415
"register-service-worker": "^1.0.0",
1516
"vue": "^2.5.13",
1617
"vue-class-component": "^6.0.0",
1718
"vue-property-decorator": "^6.0.0",
1819
"vue-router": "^3.0.1",
19-
"vuex": "^3.0.1"
20+
"vuex": "^3.0.1",
21+
"whatwg-fetch": "^2.0.3"
2022
},
2123
"devDependencies": {
2224
"@types/chai": "^4.1.0",

src/main.ts

+5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
// polyfill
2+
import 'promise-polyfill/src/polyfill';
3+
import 'whatwg-fetch';
4+
5+
// start app
16
import Vue from 'vue';
27
import App from './views/App.vue';
38
import router from './router';

src/util/cookie.ts

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/* cookie api */
2+
3+
interface CookieOptions {
4+
path?: string;
5+
expires?: number | Date;
6+
domain?: string;
7+
secure?: boolean;
8+
}
9+
10+
/* 获取cookie */
11+
export function getCookie(name: string): string {
12+
const matcher = document.cookie.match(RegExp('(?:^| )' + name + '=([^;]*)'));
13+
if (matcher !== null) {
14+
return decodeURIComponent(matcher[1]);
15+
}
16+
return '';
17+
}
18+
19+
/* 设置cookie */
20+
export function setCookie(
21+
name: string,
22+
value: string,
23+
options: CookieOptions,
24+
): boolean {
25+
if (!name) {
26+
return false;
27+
}
28+
let stringifiedAttributes: string = '';
29+
const attributes: CookieOptions = { path: '/', ...options };
30+
if (typeof attributes.expires === 'number') {
31+
const expires = new Date();
32+
expires.setMilliseconds(expires.getMilliseconds() + attributes.expires);
33+
attributes.expires = expires;
34+
}
35+
const names = Object.keys(attributes) as Array<keyof CookieOptions>;
36+
for (const key of names) {
37+
if (!attributes[key]) {
38+
continue;
39+
}
40+
stringifiedAttributes += '; ' + key;
41+
if (attributes[key] === true) {
42+
continue;
43+
}
44+
if (name === 'expires') {
45+
stringifiedAttributes +=
46+
'=' + (attributes.expires ? attributes.expires.toUTCString() : '');
47+
}
48+
stringifiedAttributes += '=' + attributes[key];
49+
}
50+
document.cookie =
51+
name + '=' + encodeURIComponent(value) + stringifiedAttributes;
52+
return true;
53+
}
54+
55+
/* 删除cookie */
56+
export function removeCookie(name: string): boolean {
57+
return setCookie(name, '', { expires: -1 });
58+
}

src/util/fetch.ts

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/* fetch api */
2+
3+
import { getCookie } from '@/util/cookie';
4+
const { devServer, proServer, token } = require('../../.config.js');
5+
const fetchServer =
6+
process.env.NODE_ENV === 'production' ? proServer : devServer;
7+
8+
/* 检查返回状态 */
9+
function checkStatus(res: Response) {
10+
const { status } = res;
11+
if (status >= 200 && status < 300) {
12+
return res.json();
13+
} else if (status === 403) {
14+
// invalid token then go login
15+
return (window.location.href = '/sign');
16+
} else {
17+
throw new Error(`[${status}]:${res.statusText}`);
18+
}
19+
}
20+
21+
function internalFetch(type: 'GET' | 'POST', isGetToken: boolean = false) {
22+
return (path: string, options: RequestInit) => {
23+
let { headers } = options;
24+
headers = headers instanceof Headers ? headers : new Headers();
25+
headers.set('Content-Type', 'application/json');
26+
if (!isGetToken) {
27+
headers.set(token, getCookie(token));
28+
}
29+
return fetch(`${fetchServer}/${path}`, options).then(checkStatus);
30+
};
31+
}
32+
33+
const get = internalFetch('GET');
34+
const post = internalFetch('POST');
35+
const login = internalFetch('POST', true);
36+
37+
export { get, post, login };

vue.config.js

+82-80
Original file line numberDiff line numberDiff line change
@@ -1,81 +1,83 @@
1+
let { devServer } = require('./.config.js');
2+
13
module.exports = {
2-
// Project deployment base
3-
// By default we assume your app will be deployed at the root of a domain,
4-
// e.g. https://www.my-app.com/
5-
// If your app is deployed at a sub-path, you will need to specify that
6-
// sub-path here. For example, if your app is deployed at
7-
// https://www.foobar.com/my-app/
8-
// then change this to '/my-app/'
9-
baseUrl: '/',
10-
11-
// where to output built files
12-
outputDir: 'dist',
13-
14-
// whether to use eslint-loader for lint on save.
15-
// valid values: true | false | 'error'
16-
// when set to 'error', lint errors will cause compilation to fail.
17-
lintOnSave: true,
18-
19-
// use the full build with in-browser compiler?
20-
// https://vuejs.org/v2/guide/installation.html#Runtime-Compiler-vs-Runtime-only
21-
compiler: false,
22-
23-
// tweak internal webpack configuration.
24-
// see https://github.com/vuejs/vue-cli/blob/dev/docs/webpack.md
25-
chainWebpack: () => {},
26-
configureWebpack: () => {},
27-
28-
// vue-loader options
29-
// https://vue-loader.vuejs.org/en/options.html
30-
vueLoader: {},
31-
32-
// generate sourceMap for production build?
33-
productionSourceMap: true,
34-
35-
// CSS related options
36-
css: {
37-
// extract CSS in components into a single CSS file (only in production)
38-
extract: true,
39-
40-
// enable CSS source maps?
41-
sourceMap: false,
42-
43-
// pass custom options to pre-processor loaders. e.g. to pass options to
44-
// sass-loader, use { sass: { ... } }
45-
loaderOptions: {},
46-
47-
// Enable CSS modules for all css / pre-processor files.
48-
// This option does not affect *.vue files.
49-
modules: false
50-
},
51-
52-
// use thread-loader for babel & TS in production build
53-
// enabled by default if the machine has more than 1 cores
54-
parallel: require('os').cpus().length > 1,
55-
56-
// split vendors using autoDLLPlugin?
57-
// can also be an explicit Array of dependencies to include in the DLL chunk.
58-
// See https://github.com/vuejs/vue-cli/blob/dev/docs/cli-service.md#dll-mode
59-
dll: false,
60-
61-
// options for the PWA plugin.
62-
// see https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa
63-
pwa: {},
64-
65-
// configure webpack-dev-server behavior
66-
devServer: {
67-
open: process.platform === 'darwin',
68-
host: '0.0.0.0',
69-
port: 8080,
70-
https: false,
71-
hotOnly: false,
72-
// See https://github.com/vuejs/vue-cli/blob/dev/docs/cli-service.md#configuring-proxy
73-
proxy: 'http://localhost:4000', // string | Object
74-
before: app => {}
75-
},
76-
77-
// options for 3rd party plugins
78-
pluginOptions: {
79-
// ...
80-
}
81-
}
4+
// Project deployment base
5+
// By default we assume your app will be deployed at the root of a domain,
6+
// e.g. https://www.my-app.com/
7+
// If your app is deployed at a sub-path, you will need to specify that
8+
// sub-path here. For example, if your app is deployed at
9+
// https://www.foobar.com/my-app/
10+
// then change this to '/my-app/'
11+
baseUrl: '/',
12+
13+
// where to output built files
14+
outputDir: 'dist',
15+
16+
// whether to use eslint-loader for lint on save.
17+
// valid values: true | false | 'error'
18+
// when set to 'error', lint errors will cause compilation to fail.
19+
lintOnSave: true,
20+
21+
// use the full build with in-browser compiler?
22+
// https://vuejs.org/v2/guide/installation.html#Runtime-Compiler-vs-Runtime-only
23+
compiler: false,
24+
25+
// tweak internal webpack configuration.
26+
// see https://github.com/vuejs/vue-cli/blob/dev/docs/webpack.md
27+
chainWebpack: () => {},
28+
configureWebpack: () => {},
29+
30+
// vue-loader options
31+
// https://vue-loader.vuejs.org/en/options.html
32+
vueLoader: {},
33+
34+
// generate sourceMap for production build?
35+
productionSourceMap: true,
36+
37+
// CSS related options
38+
css: {
39+
// extract CSS in components into a single CSS file (only in production)
40+
extract: true,
41+
42+
// enable CSS source maps?
43+
sourceMap: false,
44+
45+
// pass custom options to pre-processor loaders. e.g. to pass options to
46+
// sass-loader, use { sass: { ... } }
47+
loaderOptions: {},
48+
49+
// Enable CSS modules for all css / pre-processor files.
50+
// This option does not affect *.vue files.
51+
modules: false,
52+
},
53+
54+
// use thread-loader for babel & TS in production build
55+
// enabled by default if the machine has more than 1 cores
56+
parallel: require('os').cpus().length > 1,
57+
58+
// split vendors using autoDLLPlugin?
59+
// can also be an explicit Array of dependencies to include in the DLL chunk.
60+
// See https://github.com/vuejs/vue-cli/blob/dev/docs/cli-service.md#dll-mode
61+
dll: false,
62+
63+
// options for the PWA plugin.
64+
// see https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa
65+
pwa: {},
66+
67+
// configure webpack-dev-server behavior
68+
devServer: {
69+
open: process.platform === 'darwin',
70+
host: '0.0.0.0',
71+
port: 8080,
72+
https: false,
73+
hotOnly: false,
74+
// See https://github.com/vuejs/vue-cli/blob/dev/docs/cli-service.md#configuring-proxy
75+
proxy: devServer, // string | Object
76+
before: (app) => {},
77+
},
78+
79+
// options for 3rd party plugins
80+
pluginOptions: {
81+
// ...
82+
},
83+
};

yarn.lock

+8
Original file line numberDiff line numberDiff line change
@@ -5647,6 +5647,10 @@ promise-inflight@^1.0.1:
56475647
version "1.0.1"
56485648
resolved "https://registry.yarnpkg.com/promise-inflight/-/promise-inflight-1.0.1.tgz#98472870bf228132fcbdd868129bad12c3c029e3"
56495649

5650+
promise-polyfill@^7.1.0:
5651+
version "7.1.0"
5652+
resolved "https://registry.yarnpkg.com/promise-polyfill/-/promise-polyfill-7.1.0.tgz#4d749485b44577c14137591c6f36e5d7e2dd3378"
5653+
56505654
proxy-addr@~2.0.3:
56515655
version "2.0.3"
56525656
resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.3.tgz#355f262505a621646b3130a728eb647e22055341"
@@ -7407,6 +7411,10 @@ whatwg-encoding@^1.0.1, whatwg-encoding@^1.0.3:
74077411
dependencies:
74087412
iconv-lite "0.4.19"
74097413

7414+
whatwg-fetch@^2.0.3:
7415+
version "2.0.3"
7416+
resolved "https://registry.yarnpkg.com/whatwg-fetch/-/whatwg-fetch-2.0.3.tgz#9c84ec2dcf68187ff00bc64e1274b442176e1c84"
7417+
74107418
whatwg-url@^6.4.0:
74117419
version "6.4.0"
74127420
resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-6.4.0.tgz#08fdf2b9e872783a7a1f6216260a1d66cc722e08"

0 commit comments

Comments
 (0)