分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

nginx 解决AJAX 跨域问题。

发布时间:2023-09-06 01:08责任编辑:沈小雨关键词:nginx跨域

AJAX跨域的问题很常见,有较多的解决办法如:jsonp,设置服务端允许跨域,给请求加代理等等解决方式,我项目中常用node.js搭建中间代理的方式解决。下面我将尝试采用nginx做代理的方式解决跨域的问题。

第一步:搭建Server API,其中未设置允许跨域。get方法,返回英雄列表。(http://localhost:8081/heroes)

第二步:写页面测试ajax请求(http://localhost:8081/heroes),结果显示跨域了。

顺便说一下:如果要修改服务端只需要设置如下:

第三步:修改nginx配置文件

配置代码:

        location = /heroes {
             add_header ‘Access-Control-Allow-Origin‘ ‘*‘;
             add_header ‘Access-Control-Allow-Methods‘ ‘GET, POST, OPTIONS‘;
             add_header ‘Access-Control-Allow-Headers‘ ‘DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range‘;
             add_header ‘Access-Control-Expose-Headers‘ ‘DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range‘;
                proxy_pass http://localhost:8081;
         }

第四步:测试ajax请求,这次将第二步中的8081改成80,让ajax的请求被ngnix代理,能获得结果。







nginx 解决AJAX 跨域问题。

原文地址:http://www.cnblogs.com/rfyuanwei/p/7472625.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved