学习 / 实践 / 课外补充 / 问题 · 2020年10月1日 0

jQuery进行ajax访问时无法获得数据

报错信息:

jquery.js:18 Access to XMLHttpRequest at 'https://api.xbgit.cn/***' from origin 'https://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
send @ jquery.js:18
ajax @ jquery.js:18

解决办法:

package cn.xbgit.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Simple to Introduction
 *
 * @ProjectName: 9-29-test
 * @Package: cn.xbgit.config.CorsConfig
 * @ClassName: CorsConfig
 * @Description: [一句话描述该类的功能]
 * @Author: sky
 * @CreateDate: 2020/10/1 9:44
 * @UpdateUser: sky
 * @UpdateDate: 2020/10/1 9:44
 * @UpdateRemark: [说明本次修改内容]
 * @Version: [v1.0]
 */
@Configuration
@EnableWebMvc
public class CorsConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") //表示本应用的所有方法都会去处理跨域请求
//                .allowedOrigins("http://localhost:8081")
//                .allowedMethods("*") //表示允许通过的请求数
//                .allowedHeaders("*") //表示允许的请求头
                ;
    }
}

经过这样的配置之后,ajax可以跨域了。

查阅相关资料后的知此操作会导致安全性降低