nginx解决web跨域请求问题

发布时间:2020-11-18 19:48:25 阅读:1284次

我们知道web请求有同源策略,

所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)

如果不同源,那么就会存在跨域

比如一个html页面想调另一个域名的php接口

以下是html文件的代码

index.html

<script language=javascript src="http://zm.blog.com/js/jquery.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            type: "POST",
            url:"http://test.api.com/api.php",
            dataType:'json',
            data:{"sitename":"test","url":"http://www.test.com"},
            success:function(data){
                $("#msg").html(data.sitename +"<br>" + data.url);
                alert(data.sitename);
                alert(data.url);
            }
        });
    })
</script>
<span id="msg"></span>

以下是api.php的代码

[root@web_test public]# cat test.php 
<?php
$post=$_POST;
print_R(json_encode($post));

这个时候会提示

test.php (failed)net::ERR_FAILED xhr

这个时候我们可能通过设置nginx来解决这个问题

我们可以设置nginx

加上以下代码

location / { 
    if ($request_method = 'OPTIONS') {
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Headers 'X-Requested-With, X-CSRF-Token, Content-Type, Accept, Authorization';
        add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
        return 204;
    }
    try_files $uri $uri/ /index.php$is_args$args;
}
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers 'X-Requested-With, X-CSRF-Token, Content-Type, Accept, Authorization';
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;

重启nginx

nginx -s reload

即可正常访问

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询

转载请注明:nginx解决web跨域请求问题 出自老鄢博客 | 欢迎分享