同源策略是什么?
一个 URL 有三部分组成:协议、域名(指向主机)、端口,只有这三个完全相同的 URL 才能称之为同源。如下,能和
http://www.baidu.com/api/index.html 同源的是?URL 结果 原因 http://www.baidu.com/api2/other.html 同源 只有路径不同
https://www.baidu.com/secure.html 不同源 协议不同
http://www.baidu.com:81/api/etc.html 不同源 端口不同 ( http:// 默认端口是80)
http://news.baidu.com/api/other.html 不同源 域名不同
当使用uniapp 开发会跨域时报错
Access to XMLHttpRequest at
‘http://192.168.31.24:9998/v1/attendance/attendanceCondition?teacher_id=151&campus_id=1’
from origin ‘http://192.168.31.85:8888’ has been blocked by CORS
policy: Request header field campus is not allowed by
Access-Control-Allow-Headers in preflight response.
假设baseUrl设置成本地ip或者域名时,没有设置头部参数,不会报跨域
import uni_request from './uni_request/uni_request.js'
let baseUrl="http://192.168.31.24:9998" //报错跨域
let baseUrl="/" //成功域名映射http://192.168.31.85:8888
const request = uni_request({ // 有效配置项只有三个
baseURL: baseURL, //baseURL
})
/* 请求拦截器 */
request.interceptors.request.use((config, ...args) => {
var token = uni.getStorageSync('token');
var studentId = uni.getStorageSync('Student-Id');
if(token) config.header['Authorization'] = token;
if(studentId) config.header['Student-Id'] = studentId
return config
})
大部分都是因为同源策略导致跨域,当我们配置本地baseURL域名时可以使用**/**来做映射即可
上线配置http://******.com域名
let baseUrl = process.env.NODE_ENV==“development”?‘/’:‘http://*****.com’
H5 本地处理跨域devServer
"devServer" : {
"https" : false,
"port" : 8888,
"disableHostCheck" : true,
"proxy" : {
"/" : {
"target" : "http://192.168.31.24:9998",
"changeOrigin" : true,
"secure" : true,
"pathRewrite" : {
"^/" : "/"
}
}
}
},