首页 > 解决方案 > 如何同时打印“PUT”和“POST”方法?

问题描述

写入两个函数底部的函数有效,但另一个无效。我也没有收到错误消息。我认为交易正在发生,但没有写入任何内容。我怎样才能将两者都写入控制台?我将把控制台的打印输出放在下面。预先感谢您的回答。

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
}

标签: javascripthttprequest

解决方案


您应该使用 xhr 一次,而不是多次。要解决此问题,只需调用const xhr = new XMLHttpRequest()您需要的每个方法。


推荐阅读