ajax请求解决跨域问题 摒弃jsonp方式

原始解决此类问题  需要在 ajax上设置jsonp的方式  太笨重



请求的话设置json方式请求

    getAllPages(limit, page) {
        console.log("limit:" + limit + "  page:" + page);
        $.ajax({
            url: "http://localhost:8080/ssm-redis/getUserByPage",
            data:$.param({
                limit:limit,
                page:page
            }),
            type: 'GET',
            contentType: 'application/x-www-form-urlencoded',
            dataType:'json',
            success: function(data){
                console.log("--------------->");
                console.log("lists:" +data)
            },
        });
    }


需要在服务端做出设置

首先将对应的依赖添加到maven的pom文件中

		<dependency>
			<groupId>com.thetransactioncompany</groupId>
			<artifactId>cors-filter</artifactId>
			<version>2.6</version>
		</dependency>

同时在web.xml 文件中配置过滤器fliter

	<!-- 配置跨域请求服务 -->
	<filter>
		<filter-name>CORS</filter-name>
		<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
		<init-param>
			<param-name>cors.allowOrigin</param-name>
			<param-value>*</param-value>
		</init-param>
		<init-param>
			<param-name>cors.supportedMethods</param-name>
			<param-value>GET, POST, HEAD, PUT, DELETE</param-value>
		</init-param>
		<init-param>
			<param-name>cors.supportedHeaders</param-name>
			<param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified,app_key</param-value>
		</init-param>
		<init-param>
			<param-name>cors.exposedHeaders</param-name>
			<param-value>Set-Cookie</param-value>
		</init-param>
		<init-param>
			<param-name>cors.supportsCredentials</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CORS</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


再次请求,即可完成跨域


猜你喜欢

转载自blog.csdn.net/qq_38976693/article/details/78763744