跨域、http header设置

版权申明:未经允许请勿转载。转载前请先联系作者(hello@yeshen.org)

跨域、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 = 0let contentType = 'application/x-www-form-urlencoded'let system = navigator.platformlet 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()


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部