问题描述
前端请求某个api, 在发送http请求的模拟工具里, 能正常看到响应数据; 但是在我自己的请求的回调函数里, 却没有响应数据,虽然状态码是200
问题出现的环境背景及自己尝试过哪些方法
本地文件在chrome中调试, 已经启用跨域的插件
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
- 这是我自己写的请求
const get = function (url, success, fail, complete, context) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("app_type", 'xxxx');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
if (typeof success === 'function') {
// 响应的xhr.responseText是 ""的
console.log('response data', xhr.responseText);
success.call(context, xhr.responseText);
}
} else {
if (typeof fail === 'function') {
fail.call(context, xhr.responseText);
}
}
if (typeof complete === 'function') {
complete.call(context, xhr.responseText);
}
}
};
xhr.send();
}
- 但是http模拟工具中是可以正常响应
- chrome中的请求结果
你期待的结果是什么?实际看到的错误信息又是什么?
知道自己写请求问题出在哪里, 能正确获得响应数据
服务端可以在收到请求之后返回空字符串的,如果是自己的服务,可以在后端返回些别的内容,如果是别人的,那可能是被反爬虫机制戏弄了,需要再伪装一下。
鉴于是 GET 请求,可以直接将请求的 URL 粘贴到浏览器地址栏中访问,如果页面啥都没有的话,应该就是给你返回了个空字符串。