就一个地方需要设置:就是请求源.
1. 独立跨域(单独的某个响应实现跨域)
@app.route("/user", methods=["get", "post", "OPTIONS","PUT","DELETE"])
def user():
data = {
"username": "aa",
}
res = make_response(data)
res.headers['Access-Control-Allow-Origin'] = 'http://localhost:8080' # 关键就是这一句.
res.headers["Access-Control-Allow-Headers"] = "Content-Type"
res.headers['Access-Control-Allow-Credentials'] = 'true' # 有这个,可以cookie跨域
res.headers['Access-Control-Allow-Methods'] = "GET,POST,PUT,DELETE,OPTIONS" # 对于复杂请求必须加
return res
那么 res.headers["Access-Control-Allow-Headers"] = "Content-Type"
是什么呢?
没有的话,浏览器就会报错:
Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response 预检响应的Access-Control-Allow-Headers不允许请求头字段content-type
需要注意,“http://localhost:8080"后面不能带有”/"
网上大部分文章是: res.headers['Access-Control-Allow-Origin'] = "*"
指的是允许所有域注意星号不要写错
请求有两种,一种是简单请求,比如get,post还有复杂请求,比如put
简单请求跨域,没有要求声明方法,但是复杂请求跨域必须声明允许方法
res.headers['Access-Control-Allow-Methods'] = "GET,POST,PUT,DELETE,OPTIONS"
前端也一定要有对应的方法,不然也还是会提示跨域访问被拒绝.比如
@app.route("/user", methods=["get", "post", "OPTIONS","PUT","DELETE"])
2.全局跨域
全局跨域,就在@app.after_request 在个装饰器下添加个全局的函数
after_request 虽然叫请求后,实际上应该叫before_response响应前,是在返回响应之前处理响应
@app.after_request
def after_request(res):
resp = make_response(res)
res.headers['Access-Control-Allow-Origin'] = 'http://localhost:8080'
res.headers["Access-Control-Allow-Headers"] = "Content-Type"
res.headers['Access-Control-Allow-Credentials'] = 'true' //有这个,可以cookie跨域
res.headers['Access-Control-Allow-Methods'] = "GET,POST,PUT,DELETE,OPTIONS" //对于复杂请求必须加
return resp
@app.route('/user', methods=["POST", "OPTIONS"])
def hello_world():
data = {
"user": "user",
"password": "000000"
}
return data
3 cookie 和 session跨域
这里的session是指利用cookie存储的session
后端(服务端)参考2 全局跨域
客户端(前端) 需要注意的是,添加withCredentials = true
比如vue 中使用axios:
import axios from 'axios'
Vue.prototype.$axios = axios
axios.defaults.withCredentials = true
对于cookie跨域,'Access-Control-Allow-Origin’的域名不能为"*"!