node+koa2+axios踩坑记

踩坑一、在vue+node开发的时候,出现跨域问题,html

第一步:这时候使用nginix作反向代理,解决跨域,设置以下vue

首先打开(E:\ruanjian\nginx-1.14.2\conf)中的 nginx.conf,进行以下设置node

 

 

第二步:安装 koa2-cors 插件,在app.js里面进行以下设置ios

const cors = require('koa2-cors') // 解决跨域
app.use(cors({ exposeHeaders: ['WWW-Authenticate', 'Server-Authorization', 'Date'], maxAge: 100000, credentials: true, allowMethods: ['GET', 'POST', 'OPTIONS'], allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Custom-Header', 'anonymous','Set-Cookie'], }))

踩坑2:当有session时,设置axios请求时携带cookie失效nginx

解决为设置 axios

 

axios.defaults.withCredentials = true; //配置为true

 

理由以下:后端

 

withCredentials:默认状况下,跨源请求不提供凭据(cookie、HTTP认证及客户端SSL证实等)。经过将withCredentials属性设置为true,能够指定某个请求应该发送凭据。跨域

  • 默认值为false。
  • true:在跨域请求时,会携带用户凭证
  • false:在跨域请求时,不会携带用户凭证;返回的 response 里也会忽略 cookie

当配置了 withCredentials = true时,必须在后端增长 response 头信息Access-Control-Allow-Origin,且必须指定域名,而不能指定为*!!!cookie

参考以下: http://www.manongjc.com/article/36042.htmlsession

相关文章
相关标签/搜索