跨域、http header设置

版权申明:未经允许请勿转载。转载前请先联系作者([email protected]

跨域、http header设置

跨域本质上是为了安全。不展开讲细节了,分享一下实际写代码中遇到的问题

有几个点,
1,跨域是在服务器端设置的,服务器端没有设置,在服务器端的nginx设置也可以,要设置几个值:

Access-Control-Allow-Origin:*
Access-Control-Allow-Methods:"POST, GET, OPTIONS, DELETE"

前端基本不用做特殊设置

2,有写时候我们会用自定义的header来带一些用户信息,这个时候,服务器端也要设置下

eg:

Access-Control-Allow-Headers:X-App-Vendor

如果没有设置,可能会报这个错误

Failed to load http://yeshen.org/api/admin/session:
Request header field X-App-Vendor is not allowed by 
Access-Control-Allow-Headers in preflight response.

3,vue resource中设置header可以这样设置

function generateHeaders() {
  let deviceId = Cookie.get('X-App-Device')
  if (deviceId === undefined) {
    deviceId = 'WEB-' + Date.now().toString(36)
    deviceId += Math.random()
      .toString(36)
      .slice(2)
    deviceId += Math.random()
      .toString(36)
      .slice(3)
    deviceId = deviceId.toUpperCase()
    Cookie.set('X-App-Device', deviceId)
  }
  let platform = 0
  let contentType = 'application/x-www-form-urlencoded'
  let system = navigator.platform
  let info = navigator.userAgent
    .toLowerCase()
    .match(/(msie|firefox|chrome|opera|version).*?([\d.]+)/)
  let vendor =
    info && info.length >= 3
      ? info[1].replace(/version/, "'safari") + info[2]
      : 'null'
  return {
    'Content-Type': contentType,
    'X-App-Device': deviceId,
    'X-App-Platform': platform,
    'X-App-Vendor': vendor,
    'X-App-System': system
  }
}

...

//here is setting
Vue.http.options.headers = generateHeaders()

你可能感兴趣的:(H5/Mini-Program)