记一次header跨域与cookie共享
最近把左边的传统模式,换成了右边通过js直接调api拿数据并渲染,于是变出现了ajax的跨域问题:
XMLHttpRequest cannot load http://api.abc.com/?s=user/account_log&v=1.0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://m.abc.com' is therefore not allowed access.
api项目都为post请求且返回结果为json,为了不改动api,于是没用jsonp,而是采用header,修改api.abc.com的nginx配置:
add_header Access-Control-Allow-Origin http://m.abc.com;
请求成功之后发现cookie无法共享,在ajax里带上参数:
crossDomain: true,
xhrFields:{
withCredentials:true
},
出现错误:
XMLHttpRequest cannot load http://api.abc.com/?s=user/account_log&v=1.0. The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. Origin 'http://m.abc.com' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
再次修改api.abc.com的nginx配置:
add_header Access-Control-Allow-Credentials true;
至此正常访问。
-------------------------2017.10.13 更新-----------------------------
如果Access-Control-Allow-Origin配置的是通配的 * ,这里还会报另一个错误
Failed to load http://api.abc.com/?s=user/account_log&v=1.0: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://m.abc.com' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
-------------------------2017.05.23 更新-----------------------------
为了配合新增m的三级域名,调整api.abc.com的nginx配置:
server {
listen ;
listen ;
server_name api.abc.com;
index index.php;
root /datas/htdocs/abc_api; ssl on;
ssl_certificate /etc/ssl/ssl.crt;
ssl_certificate_key /etc/ssl/ssl.key; location ~ .*\.php?$ {
set_by_lua $http_referer_test '
if ngx.var.http_referer ~= nil then
tt = string.match(ngx.var.http_referer, "//%w+%.?m%.abc%.com");
end
if tt == nil or tt == "" then
tt = "//m.abc.com";
end
return tt;
'; proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://127.0.0.1:9504;
add_header Access-Control-Allow-Origin $scheme:$http_referer_test;
add_header Access-Control-Allow-Credentials true;
} access_log /datas/log/www/access.abc_api.log main;
error_log /datas/log/www/error.abc_api.log;
}
最新文章
- Bigtable 论文 阅读笔记 - 原理部分
- C++ 第二次课堂作业(反转链表)
- JSP内置对象整理(转)
- c++多线程参数的传递
- python 发送安全邮件
- vue初级学习--控制台创建vue项目
- 关于new,delete,malloc,free的一些总结
- C语言第二次博客作业——分支结构
- LeetCode之“树”:Binary Tree Preorder &;&; Inorder &;&; Postorder Traversal
- dictionary.go
- springboot 注册dao层 service 层
- 算法与数据结构(四) 图的物理存储结构与深搜、广搜(Swift版)
- 20164318 毛瀚逸-----EXP5 MSF基础应用
- kong插件应用
- 【bzoj 2002】弹飞绵羊
- P2731 骑马修栅栏 欧拉函数
- HDU2167(SummerTrainingDay02-D 状态压缩dp)
- ArrayList与LinkedList的基本添加删除方法 模拟栈 队列
- redis 命令行查看修改配置文件项、配置文件说明
- Jmeter----逻辑控制器(Logic Controller)