浏览器本身的特点
http 默认端口号 80
https 默认端口号 443
当 WEB服务器 和 数据服务器 不是同一台服务器,则会报 ‘服务器不允许当前源访问’
跨域问题的产生及其价值意义
1.JSONP跨域解决方案的底层原理
客户端:
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script> $.ajax({ url: "http://127.0.0.1:8001/list", method: "get", dataType: "jsonp", success: (res) => { console.log(res); }, }); </script>
服务端:
let express = require("express"); let app = express(); app.listen(8001, (_) => { console.log("OK!"); }); app.get("/list", (req, res) => { let { callback = Function.prototype } = req.query; let data = { code: 0, message: "测试", }; res.send(`${callback}(${JSON.stringify(data)})`); });
2.基于 iframe的跨域解决方案
window.name
document.domin
location.hash
post message
3.CORS跨域资源共享
客户端
import axios from "axios"; import qs from "qs"; axios.defaults.baseURL = "http://127.0.0.1:3000"; axios.defaults.timeout = 10000; axios.defaults.withCredentials = true; /** * 设置请求传递数据的格式(看服务器要求什么格式) * x-www-form-urlencoded */ axios.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded"; axios.defaults.transformRequest = (data) => qs.stringify(data); /** * 设置请求拦截器 */ axios.interceptors.request.use( (config) => { let token = localStorage.getItem("token"); token && (config.headers.Authorization = token); return config; }, (error) => { return Promise.reject(error); } ); /** * 响应拦截器 */ axios.interceptors.response.use( (response) => { return response.data; }, (error) => {} );
服务端
app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", ""); res.header("Access-Control-Allow-Credentials", true); res.header( "Access-Control-Allow-Headers", "PUT,POST,GET,DELETE,OPTIONS,HEAD" ); res.header( "Access-Control-Allow-Methods", "Content-Type,Content-Length,Authorization,Accept,X-Requested-With" ); req.method === "OPTIONS" ? res.send("CURRENT SERVICES SUPPORT CROSS DOMAIN REQUESTS!") : next(); });
4.基于 http proxy 实现跨域请求
nginx反向代理