在jQuery中使用AJAX時,我有奇怪的情況。 我在後端側使用的node.js與express.js一起,我寫了我的後端在這裏簡單的途徑:成功處理程序後AJAX parseerror被稱爲
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執行請求後,它會觸發成功回調,然而,錯誤回調被觸發爲 好。
正如你可能已經注意到,第一個日誌來自成功的回調外,其餘都來自錯誤回調。
任何想法發生在這裏以及如何解決這個問題?感謝
---- ----編輯
我找到錯誤的根源,所以在短期我爲了使用ES6功能使用巴貝爾和我使用類客戶端上的
如果我謹請求構造器,如:
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();
它的工作原理!沒有錯誤回調被調用。
現在我的問題,這是如何發生的?爲什麼?以及如何將請求調用分離到一個函數?在構造函數中調用請求並不是我想要的,因爲可能我想在我的類的某處封裝請求。
你是說成功和錯誤回調觸發一個AJAX?這絕不應該發生。這些日誌可能來自不同的Ajax請求。 – Ozan
我同意@Ozan,...也嘗試使用函數(){}而不是()=> {} –
都來自一個ajax,我試圖添加一些日誌,以確保它來自一個ajax也添加beforeSend參數並記錄下來,實際上它來自一個ajax請求.. 之前發送也調用過一次 – tronic