- 先让我们来抛出问题.什么是跨域,它是怎么形成的,从而怎么解决跨域问题. 什么跨域
协议,端口,域名相同的三者百分百相同就是同源.如果又一项不相同就会产生跨域问题
目录结构
根目录
├── public
│ ├── js
└── axios.js
│ └── index.html # 提前准备好的页面
└── server.js
准备素材
index.html中的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="btn1_get">接口测试1:get请求带参数</button>
<button id="btn2_post"> 接口测试2:post-传递普通键值对</button>
<hr/>
<button id="btn3_postJSON">接口测试3:post-传递json</button>
<hr/>
<form id="myform">
<input type="text" name="title">
<input type="file" name="cover">
</form>
<button id="btn4_formdata">接口测试4:post-传递formdata</button>
<hr/>
<script src="./js/axios.js"></script>
<script>
document.getElementById('btn1_get').addEventListener('click',() => {
axios.get('http://localhost:3000/getapi', {params: {a:1,b:2}})
})
var obj = {
"name":"abc",
"address":{
"a":1,
"b":2,
"info":"c"
}
}
document.getElementById('btn2_post').addEventListener('click', () => {
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('http://localhost:3000/post', params, {
headers: {"content-type":"application/x-www-form-urlencoded"}})
})
document.getElementById('btn3_postJSON').addEventListener('click', () => {
axios.post('http://localhost:3000/postJSON', obj)
})
document.getElementById('btn4_formdata').addEventListener('click', () => {
console.log(1)
var fd = new FormData(document.getElementById('myform'));
axios.post('http://localhost:3000/publish',
fd
)
})
</script>
</body>
</html>
后端
// 实现get接口
const express = require('express')
const app = express();
app.use(express.static('public'))
// 引入bodyParse包
const bodyParser = require('body-parser')
// 使用包. 则在后续的post请求中
// 会自动加入req.body属性,这个属性中就包含了post请求所传入的参数
// 处理普通的键值对格式
// Content-Type: application/x-www-form-urlencoded
app.use(express.urlencoded())
// 处理JSON格式
// Content-Type: application/json;
app.use(express.json())
// 引入multer包
const multer = require('multer');
// 配置一下multer
// 如果本次post请求涉及文件上传,则上传到uploads这个文件夹下
// Content-Type: multipart/form-data;
var upload = multer({ dest: 'uploads/'})
// 实现接口1: get类型接口
// 返回所传入的参数,并附上上时间戳
app.get('/getapi',(req,res)=>{
// 通过 req.query快速获取传入的参数
console.log(req.query);
let obj = req.query
obj._t = Date.now();
res.json( obj )
})
// 实现接口2:普通post 键值对
app.post('/post',(req,res)=>{
// 希望在后端收到post传参
console.log(req.body);
let obj = req.body
obj._t = Date.now();
res.json(obj)
})
// 实现接口3:用来JSON格式的数据
// Content-Type: application/json;
app.post('/postJSON',(req,res)=>{
// 希望在后端收到post传参
console.log(req.body);
// res.send('/postJSON')
res.json( req.body )
})
// 实现接口4:接口formDate
app.post('/publish',upload.single('cover'),(req,res)=>{
console.log('publish...')
//upload.single('cover')
// 这里的cover就是在页面中表单元素中的name
// <input type="file" name="cover" />
// 把要上传文件放在指定的目录
console.log(req.file);
// 其它参数,还是在req.body中找
console.log(req.body);
res.json({code:200,msg:'上传成功',info:req.file.path})
})
app.listen(3000,()=>{
console.log('express应用在3000端口启动了');
})
问题演示
把前端代码单独运行,就会报错了.
是什么原因导致了浏览器跨域报错
跨域错误,不同源的ajax请求===>报跨域错误
浏览器向web服务器发起http请求时 ,如果同时满足以下三个条件时,就会出现跨域问题,从而导致ajax请求失败:
浏览器向web服务器发起http请求时 ,如果同时满足以下三个条件时,就会出现跨域问题,从而导致ajax请求失败:
(1)请求响应双方url不同源。
双方url:发出请求所在的页面 与 所请求的资源的url
以下就是不同源的:
从http://127.0.0.1:5500/message_front/index.html 请求http://localhost:8080/getmsg
网络中不同源的请求有很多。
(2)请求类型是xhr请求。就是常说的ajax请求。不是请求图片资源,js文件,css文件等
(3)浏览器觉得不安全。跨域问题出现的基本原因是浏览器的同源策略。同源策略是一个重要的安全策略,它限制一个origin的文档或者它加载的脚本如何能与另一个源的资源进行交互。
注意,错误是发生在浏览器端的。请求是可以正常从浏览器发到服务器端,服务器也可以处理请求,只是返回到浏览器端时出错了。
解决思路
请求响应双方url不同源
- 服务器代理
请求是ajax
- 改发JSONP
浏览器觉得不安全 (后端还是能收到请求的)
- 可以安装一个浏览器插件
allow-control-allow-origin绕过同源策略。 - 用postman软件测试
- CORS