在 jQuery 中使用 AJAX 时,我遇到了奇怪的情况。 我在后端使用node.js 和express.js,这里是我为后端编写的简单路线:
app.all('/*', (request, response, next) => {
response.header('Access-Control-Allow-Origin', '*');
response.header('Access-Control-Allow-Methods', 'POST,GET');
response.header('Access-Control-Allow-Headers', 'Content-Type,accept,access_token,X-Requested-With');
next();
});
app.post('test', (request, response) => {
response.json(
{
"message": "success",
"data" : "test"
}
);
// I also tried to chain .status(200) before calling .json(), the problem still occur
});
现在在前端,我使用以下代码来执行请求:
export class TestPage {
constructor() {
this._name = 'test';
}
get name() {
return this._name;
}
performRequest() {
$.ajax({
type: 'POST',
url: 'localhost:15000/test',
data: { "test": "nothing" },
dataType: 'json',
success: (response) => {
console.log(response);
},
error: (xhr, status, err) => {
console.log(xhr.responseText);
console.log(status);
console.log(err);
}
});
}
}
并从我的主脚本中调用该类,如下所示:
import { TestPage } from './TestPage'
let test = new TestPage();
test.performRequest();
现在AJAX执行请求后,会触发成功回调,但也会触发错误回调。
您可能会注意到,第一个日志来自成功回调,其余日志来自错误回调。
你知道这里发生了什么以及如何解决这个问题吗?谢谢
---- 编辑 ----
我找到了错误的根源,所以简而言之,我使用 babel 来使用 ES6 功能,并在客户端使用 class
如果我将请求移至构造函数,例如:
export class TestPage {
constructor() {
this._name = 'test'
$.ajax({
type: 'POST',
url: 'localhost:15000/test',
data: { "test": "nothing" },
dataType: 'json',
success: (response) => {
console.log(response);
},
error: (xhr, status, err) => {
console.log(xhr.responseText);
console.log(status);
console.log(err);
}
});
}
get name() {
return this._name;
}
}
并调用它:
let test = new TestPage();
它有效!没有调用错误回调。
现在我的问题是,这是怎么发生的?为什么?以及如何将请求调用分离到函数?在构造函数中调用请求不是我想要的,因为我可能想将请求封装在类中的某个位置。
最佳答案
我无法重现该问题(我正在使用 babel.js 来启用 ES6),我怀疑您在此处发布的代码是您的实际代码。
但我的建议是:
- 确保日志来自相应的 ajax 请求,而不是来自其他请求。 (就像@Ozan 说的,一定要仔细检查)
- 确保您的回调不会引发错误。 (如果您的实际代码与本文不同)
- 尝试通过计划 JavaScript 发出请求。
- 尝试从服务器端记录
request
对象,也许你会发现一些有用的东西 - 有点难看,但您可以尝试手动解析响应,删除
dataType: 'json'
并在客户端使用JSON.parse(response)
来检索JSON 对象,使用try-catch
block 可能会在解析失败时有所帮助。
但是就像 @Ozan 所说,这样的事情永远不应该发生,请发布您的实际/完整代码,以防有所不同。
关于javascript - 调用成功处理程序后出现 AJAX 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38869193/