客户端跨域访问(CROS)之jsonp详解

本文深入探讨了JSONP(JSON with Padding)的概念,它是一种用于跨域数据获取的简便方法,绕过了XMLHttpRequest同源策略限制。通过使用script标签和回调函数,实现从不同域名获取数据,简化了跨域请求的复杂性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jsonp is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send ajax(XMLHttpRequest) request to a different domain.)

So - instead of using XMLHttpRequest we have to use script html tags, the ones you usually use to load js files, in order for js to get data from another domain. Sounds weird?

Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data";

You will end up with a script segment that looks like this after it loads the data:

<script>
{['some string 1', 'some data', 'whatever data']}
</script>

However this is a bit inconvenient, because we have to fetch this array from script tag. So jsonp creators decided that this will work better(and it is):

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";

Notice my_callback function over there? So - when jsonp server receives your request and finds callback parameter - instead of returning plain js array it'll return this:

my_callback({['some string 1', 'some data', 'whatever data']});

See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data. That's all there is to know about jsonp: it's a callback and script tags.

NOTE: these are simple examples of JSONP usage, these are not production ready scripts.

RAW javascript demonstration (simple twitter feed using jsonp)

</pre><pre name="code" class="html"><html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>
Basic jQuery example (simple twitter feed using jsonp)

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>

Note:利用jsonp 跨域访问返回数据类型只能是 json 格式


转载地址:

http://stackoverflow.com/questions/17874730/how-to-make-cross-domain-request



### 解决问题的CORS配置方法 在前后端分离的应用中,问题(Cross-Origin Resource Sharing,CORS)是一个常见的挑战。以下是几种在不同框架中配置CORS以解决问题的方法。 #### Spring Boot 中的 CORS 配置 在 Spring Boot 项目中,可以通过多种方式实现全局支持。以下是两种主要的实现方法: #### 方法一:使用 CorsFilter 过滤器 通过创建一个 `CorsFilter` 的 Bean 来实现支持。这种方式适用于需要对所有请求进行统一处理的场景[^1]。 ```java package com.college.collegesystem.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); // 允许任何访问 corsConfiguration.addAllowedOrigin("*"); // 允许任何请求头 corsConfiguration.addAllowedHeader("*"); // 允许任何请求方法 corsConfiguration.addAllowedMethod("*"); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } } ``` #### 方法二:通过 WebMvcConfigurer 配置 另一种方式是通过实现 `WebMvcConfigurer` 接口,并重写 `addCorsMappings` 方法来配置规则。这种方式更加灵活,可以针对不同的路径设置不同的规则[^3]。 ```java package com.college.collegesystem.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfiguration implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 添加路径规则 .allowCredentials(true) // 是否允许在的情况下传递 Cookie .allowedOriginPatterns("*") // 允许请求来源的规则 .allowedMethods("*") // 允许所有的 HTTP 方法 .allowedHeaders("*"); // 允许所有的请求头 } } ``` #### ThinkPHP 5.1 中的 CORS 配置 对于 ThinkPHP 5.1 框架,可以通过行为类(Behavior)的方式实现支持。以下是一个示例代码[^4]: ```php <?php namespace app\api\behavior; use think\Response; class CORS { public function appInit() { header('Access-Control-Allow-Origin: *'); // 允许所有访问地址 header("Access-Control-Allow-Headers: token,Origin, X-Requested-With, Content-Type, Accept"); // 设置你要请求的头部信息 header('Access-Control-Allow-Methods: POST,GET'); // 设置你请求的方式 header('Access-Control-Allow-Credentials: false'); // 设置是否允许 cookie if (request()->isOptions()) { exit(); // 如果是预检请求,直接返回 } } } ``` ### 注意事项 - 在生产环境中,建议不要使用通配符 `*`,而是明确指定允许的名,以提高安全性。 - 如果需要支持带凭证(如 Cookie 或 Token)的请求,则必须将 `allowCredentials` 设置为 `true`,同时不能使用通配符 `*` 作为允许的名。 ```python # 示例:Python Flask 中的 CORS 配置 from flask import Flask from flask_cors import CORS app = Flask(__name__) CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True) @app.route('/') def hello_world(): return 'Hello, World!' ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值