如何修复Ajax POST请求中的CORS跨域问题
解决本地Ajax请求的CORS错误
问题重现
你的Ajax请求代码:
$.ajax({ type: "POST", data: { id : '1234', name : 'test', }, url: "https://testdomain.com/test.php", success: function (response) { console.log(response); } else { console.log('error); } } });
出现的CORS错误(翻译后):
从源 'http://localhost/' 访问 'https://testdomain.com/test.php' 的XMLHttpRequest已被CORS策略阻止:'Access-Control-Allow-Origin' 头包含无效值。
另外你的Ajax代码存在语法错误:success回调里错误嵌套了} else {,且console.log('error);缺少闭合单引号,修正后的代码如下:
$.ajax({ type: "POST", data: { id : '1234', name : 'test', }, url: "https://testdomain.com/test.php", success: function (response) { console.log(response); }, error: function() { console.log('error'); } });
错误原因
这个CORS错误是因为目标服务器(testdomain.com)返回的Access-Control-Allow-Origin头值无效,常见情况包括:
- 域名格式错误(比如多了末尾斜杠,写成
http://localhost/而非http://localhost) - 服务器重复设置了多次
Access-Control-Allow-Origin头 - 头值设置为不符合规则的内容
解决办法
如果你能控制目标服务器(testdomain.com)
- 修改
test.php,在输出任何内容之前添加正确的CORS头:// 允许localhost访问,注意不要加末尾斜杠 header("Access-Control-Allow-Origin: http://localhost"); // 如需允许所有域名(仅测试环境使用,生产环境禁止) // header("Access-Control-Allow-Origin: *"); // POST请求额外需要允许对应的方法和请求头 header("Access-Control-Allow-Methods: POST"); header("Access-Control-Allow-Headers: Content-Type"); - 检查服务器配置(如Nginx、Apache),确保没有重复设置
Access-Control-Allow-Origin头,避免冲突。
如果你无法控制目标服务器
- 使用本地反向代理工具:比如用Node.js编写简单代理脚本,将请求转发到目标服务器,绕过CORS限制。
- 临时使用浏览器CORS插件:比如
Allow CORS: Access-Control-Allow-Origin,仅用于本地测试,不能用于生产环境。 - 将代码部署到与目标服务器同域名的环境中测试,同源请求不会触发CORS限制。
内容的提问来源于stack exchange,提问作者Kannan Raju
相关产品推荐
相关产品推荐

