javascript - 如何同时打印“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
}
解决方案
您应该使用 xhr 一次,而不是多次。要解决此问题,只需调用const xhr = new XMLHttpRequest()
您需要的每个方法。
推荐阅读
- mysql - MYSQL JSON - 在其兄弟键值上使用 WHERE 提取部分 JSON 字段
- jmeter - Jmeter请求不断给出403邮递员工作和浏览器工作的地方
- python - 使用 Scrapy 提取数据并遇到 css.seletor 问题
- c# - 在 Blazor 中为客户端和服务器使用相同的授权策略
- vuejs2 - 从 url 更新路由器链接参数
- azure-api-management - Azure API 管理是否具有计量功能 - 例如:按传输的字节数或按 API 调用数衡量?
- multithreading - Spring Boot 多线程
- webmethods - webMethods 集成需要许可证文件
- swift - 我可以从单元格中调用集合视图的重新加载数据吗?
- pyqt5 - 将pyqt5 Gui与python服务器和多个python客户端一起使用时,如何在具有唯一ID的远程客户端上运行命令