完整示例代码参考SetCookie
目录
Server
cnpm i -g express-generator pm2
express SetCookieServer
# cd SetCookieServer
cnpm i
cnpm i --save express-cors
vim app.js
// 省略了未修改的代码
var app = express();
var cors = require('express-cors');
app.use(cors({
allowedOrigins: [
'http://localhost:8000'
],
}));
// 省略了未修改的代码
关于CORS更多介绍参考MDN - HTTP访问控制(CORS)
vim routes/index.js
var express = require('express');
var router = express.Router();
router.post('/login', function(req, res, next) {
res.cookie('ZHCMD_SESS', 'cookie-from-node', { domain: 'localhost', expires: new Date(Date.now() + 1000000000), httpOnly: true })
res.send({ msg: 'success' });
});
router.get('/list', function(req, res, next) {
res.send({ msg: JSON.stringify(req.cookies) });
});
module.exports = router;
pm2 start bin/www
Web
cnpm i -g dva-cli
dva new SetCookieWeb
# SetCookieWeb
vim src/routes/IndexPage.js
import React from 'react';
export default class IndexPage extends React.Component {
login(options) {
fetch('http://localhost:3000/login', options)
.then((res) => {
return res.json();
})
.then((data) => {
alert(JSON.stringify(data));
})
.catch((err) => {
throw err;
});
}
render() {
return (
<div>
<div
onClick={() => {
this.login( {
method: 'POST',
});
}}
>无credentials</div>
<div
onClick={() => {
this.login( {
method: 'POST',
credentials: 'include',
});
}}
>有credentials</div>
</div>
);
}
};
vim src/routes/ListPage.js
import React from 'react';
export default class ListPage extends React.Component {
list(options) {
fetch('http://localhost:3000/list', options)
.then((res) => {
return res.json();
})
.then((data) => {
alert(JSON.stringify(data));
})
.catch((err) => {
throw err;
});
}
render() {
return (
<div>
<div
onClick={() => {
this.list( {
method: 'GET',
});
}}
>无credentials</div>
<div
onClick={() => {
this.list( {
method: 'GET',
credentials: 'include',
});
}}
>有credentials</div>
</div>
);
}
};
Test
npm start
浏览器打开 http://localhost:8000/#/
- 点击"无credentials"
弹出框如下
cookie如下
- 点击"有credentials"
弹出框如下
cookie如下
浏览器打开 http://localhost:8000/#/list
- 点击"无credentials"
弹出框如下
- 点击"有credentials"
弹出框如下
关于fetch更多介绍参考【翻译】这个API很“迷人”——(新的Fetch API)