簡體   English   中英

如何同時打印“PUT”和“POST”方法?

[英]How can I print the “PUT” and “POST” method at the same time?

寫在兩個函數底部的 function 可以工作,但另一個不工作。 我也沒有收到錯誤消息。 我認為交易正在發生,但沒有寫入任何內容。 我怎樣才能將兩者都寫入控制台? 我將把控制台的打印輸出放在下面。 預先感謝您的回答。

class Request {
    constructor() {
        this.xhr = new XMLHttpRequest
    }

    post(url, data, callback) {
        this.xhr.open("POST", url)
        this.xhr.setRequestHeader("Content-type", "application/json")
        this.xhr.onload = () => {
            if (this.xhr.status === 201) {
                callback(null, this.xhr.responseText)
            } else {
                callback("Hata", null)
            }
        }
        this.xhr.send(JSON.stringify(data))
    }

    put(url, data, callback) {
        this.xhr.open("PUT", url)
        this.xhr.setRequestHeader("Content-type", "application/json")
        this.xhr.onload = () => {
            if (this.xhr.status === 200) {
                callback(null, this.xhr.responseText, callback)
            } else {
                callback("Hata", null)
            }
        }
        this.xhr.send(JSON.stringify(data))
    }
}

const request = new Request()



request.post("https://jsonplaceholder.typicode.com/albums", {
    userId: 9,
    title: "Thriller"
}, function (error, response) {
    if (error === null) {
        console.log(response);
    } else {
        console.log(error);
    }
})

request.put("https://jsonplaceholder.typicode.com/albums/9", {
    userId: 2,
    title: "Thriller"
}, function (error, response) {
    if (error === null) {
        console.log(response);
    } else {
        console.log(error);
    }
})
// Console Print
{
  "userId": 2,
  "title": "Thriller",
  "id": 9
}

您應該使用 xhr 一次,而不是多次。 要解決此問題,只需在您需要的每個方法中調用const xhr = new XMLHttpRequest()即可。

您只創建了一個名為Request object 的request request.post()的第一次調用使用this.xhr來執行 POST,但在異步過程完成之前,您正在調用request.put()來執行 PUT,實際上忽略了之前的 POST。

解決此問題的一種簡單方法是創建兩個Request對象:

const request = new Request()
const request2 = new Request()

request.post("https://jsonplaceholder.typicode.com/albums", {
    userId: 9,
    title: "Thriller"
}, function (error, response) {
    if (error === null) {
        console.log(response);
    } else {
        console.log(error);
    }
})

request2.put("https://jsonplaceholder.typicode.com/albums/9", {
    userId: 2,
    title: "Thriller"
}, function (error, response) {
    if (error === null) {
        console.log(response);
    } else {
        console.log(error);
    }
})

您還可以重構代碼以使用fetch()代替。 其他可能的解決方案: 在 JavaScript 中,我/應該如何使用異步/等待與 XMLHttpRequest?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM