运行项目结构
客户端启动命令为:nodemon demos/22.js
浏览器是用虚拟服务器,mac的MAMP启动,访问链接是http://lianxi.com/node-koa/ex...
实际场景是:webpack启动vue,koa启动后台,vue调用koa接口。这里是为了方便描述调试,所以单独建的demo,意思就是跨域,对跨域做了处理,仍然失败
代码如下:
服务器端:
const Koa = require('koa');
const Router = require('koa-router');
// const cors = require('koa-cors');
const cors = require('koa2-cors');
const app = new Koa();
const router = new Router();
// 具体参数我们在后面进行解释
var corsOptions = {
origin: 'http://lianxi.com',
credentials: true,
maxAge: '1728000'
//这一项是为了跨域专门设置的
}
app.use(cors(corsOptions))
router.get('/', function (ctx, next) {
// ctx.router available
ctx.response.body = 222;
});
router.post('/loginVarify', function (ctx, next) {
console.info('view',ctx.cookies.get('view'))
// ctx.router available
const n = Number(ctx.cookies.get('view') || 0) + 1;
ctx.cookies.set('view', n, { httpOnly: false});
// ctx.response.set('Access-Control-Allow-Credentials', true);
// ctx.response.set('Access-Control-Allow-Origin', 'http://lianxi.com');
ctx.response.body = { data: 222 };
});
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000);
html:
$.ajax({
url:'http://192.168.1.105:3000/loginVarify',
method:'post',
xhrFields: {
withCredentials: true
}
}).then(function(res){
console.info(res)
})
最后一个页面的url呢?请求是的
lianxi.com
这个域的一个网页吧,不然面板也不会这么显示...看不到是正常现象,原因是:
因为你打开的不是
localhost:3000
的网页。你的电脑打开过成百上千个网页,每个域都有它的cookie,如果你打开某个页面,从开发者面板能看到所有域的cookie
怎么看的过来?所以只会显示当前域的cookie
。 当然如果你的页面有iframe
之类的,那么面板就会显示多个域的cookie
。所以你想要看到view
的话,你的页面应该有个localhost:3000
上的iframe
,或者是在localhost:3000
域上的html文件。和
lianxi.com
是没关系的。你的
cors
的设置是,只有在lianxi.com
这个域的页面才能向你的Koa服务器发请求并得到返回值,其他域向koa发的请求即使在network
面板能看到响应也无法在js中获取。