this.http写post方法
时间: 2023-10-04 09:13:42 浏览: 58
在 JavaScript 中,可以使用 XMLHttpRequest 或 Fetch API 来发送 POST 请求。以下是使用 XMLHttpRequest 的示例代码:
```javascript
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
};
xhr.onerror = function() {
console.error(xhr.statusText);
};
xhr.send(JSON.stringify(data));
```
其中,`url` 是请求的地址,`data` 是要发送的数据。在 `setRequestHeader` 中设置 Content-Type 为 application/json,表示发送的数据是 JSON 格式的。在 `send` 方法中,将数据转换成 JSON 字符串后发送。
如果使用 Fetch API,可以这样写:
```javascript
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify(data)
}).then(response => {
if (response.ok) {
return response.text();
} else {
throw new Error('Network response was not ok');
}
}).then(text => {
console.log(text);
}).catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
```
这里使用了 Promise 和 fetch 函数。在 fetch 函数中,设置 method 为 POST、headers 中的 Content-Type 为 application/json,body 中传入要发送的数据。在 then 方法中,处理响应结果的逻辑。如果响应正常,将响应内容转换成文本格式,并输出到控制台。如果出现错误,则输出错误信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)