鍍金池/ 問答/HTML/ 使用koa2如何跨域向其他IP地址寫入cookie?

使用koa2如何跨域向其他IP地址寫入cookie?

問題提要:
后臺需要對正式IP地址加上/admin后綴,所以在vue的路由配置中使用mode: 'history'。webpack打包后放置在node寫的一個web服務(wù)器(port3000)上。
web服務(wù)器上登錄接口會向前端發(fā)送username,role,token,3個cookie。
使用koa2的ctx.cookies.set方法寫了3條set-cookie語句在相應(yīng)上:

  • ctx.cookies.set('username', username, config);
  • ctx.cookies.set('role', role, config);
  • ctx.cookies.set('token', token, config);

其中config沒有對domain設(shè)置,配置如下:

{
    signed: true,    //token設(shè)置為true,username和role則由另一個配置設(shè)置為false
    expires: 1000*3600*24,
    maxAge: 1000*3600*24,
    path: '/admin',
    domain: '47.98.37.125',
    httpOnly: false
}

在整個web服務(wù)器中,對所有接口都將其設(shè)置了允許跨域?qū)懭?同時前端頁面在開發(fā)中對axios的默認配置中將withCredentials設(shè)置為true;

//vue
axios.defaults.withCredentials = true;

//node web服務(wù)器
ctx.set("Access-Control-Allow-Credentials", true);

正式IP地址通過nginx代理web服務(wù)器IP地址

問題:
在同IP地址下進行登錄時不管帶不帶3000端口號都能向瀏覽器寫入cookie,為什么不同的IP地址沒辦法寫入cookie?
就算是在ctx.cookies.set配置中將domain設(shè)置為目標IP也無法寫入,請問是什么原因造成的?有沒有其他方案解決?
對vue的路由設(shè)置了mode: 'history'后我在服務(wù)器中使用了connect-history-api-fallback中間件,并將其放置在接口中間件前面,這會不會影響到這個問題?如果將其放置在接口中間后好像會因為還未從頁面請求中寫入token造成沒有權(quán)限,陷入了一個死循環(huán)。

回答
編輯回答
故林

Cookie具有不可跨域名性。根據(jù)Cookie規(guī)范,瀏覽器訪問Google只會攜帶Google的Cookie,而不會攜帶Baidu的Cookie。Google也只能操作Google的Cookie,而不能操作Baidu的Cookie。
domain:設(shè)置可以訪問該Cookie的域名,但這個是針對子域名或父域名來說的

2017年7月4日 05:39