没有前端如何测试后端跨域问题

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

一、问题

前段时间对项目中的跨域做了相关的处理网上有很多跨域的解决方案。前端解决后端解决nginx代理解决。我采用的是在后端中使用Cors来解决跨域的问题。但是前端项目还没有搭建起来并不知道Cors的解决方案是否会生效于是在今天进行了测试。

二、解决方案

  • 直接在浏览器中打开控制台进行测试。
    在这里插入图片描述
  • 浏览器的控制台console直接输入代码
    GET请求
var token= "你的token"; //没有就省略
var xhr = new XMLHttpRequest();
xhr.open('GET', '请求类路径');
xhr.setRequestHeader("x-access-token",token); //没有就省略
xhr.send(null);
xhr.onload = function(e) {
    var xhr = e.target;
    console.log(xhr.responseText);
}

POST请求

var xhr = new XMLHttpRequest();
xhr.open('POST', '请求路径',true);
xhr.setRequestHeader('content-type', 'application/json');
var sendData = {salesmanTel:"4564564"};
 //将用户输入值序列化成字符串
xhr.send(JSON.stringify(sendData));
xhr.onload = function(e) {
    var xhr = e.target;
    console.log(xhr.responseText);
}

注意使用浏览器测试如果不生效有可能是你没有打开一个网站。比如google浏览器你不可以在google的首页测试是没有用的。

三、思路

  • 我们的项目是基于springboot搭建的java项目配置了相关的bean让其对请求进行拦截处理。
public class DevopsCorsFilter {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 好像需要制定域
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}
  • 但是因为不确定这种解决方案可以到达跨域的要求为了方便测试我先使用spring自带的@CrossOrigin注解来进行跨域的处理 。
  • 对于@CrossOrigin注解大家可以参考这篇文章 @crossOrigin介绍及使用
  • 如果我使用 @CrossOrigin 再加上使用浏览器跨域访问解决那就说明我上面 CorsConfiguration bean的配置是正确的。
    在这里插入图片描述

四、测试

  • 在浏览器输入相关的配置我的接口没有做鉴权所有没有token
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8081/devops/app/user/getPageQuery');
xhr.send(null);
xhr.onload = function(e) {
    var xhr = e.target;
    console.log(xhr.responseText);
}
  • 在浏览器执行后 结果如下
    在这里插入图片描述
  • @CrossOrigin注解注释掉后 结果如下 在这里插入图片描述
  • 由此可见浏览器中是可以测试跨域问题的。
  • 这个时候 我再将 我的 CorsConfiguration bean注入到spring中
    在这里插入图片描述
  • 在浏览器这测试结果如下
    在这里插入图片描述

五、总结

如果看到这里了说明你还是用心读完了。遇到问题不可怕找对方案解决问题就好了。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6