前端向后端发送post请求
时间: 2023-09-25 17:09:25 浏览: 38
在前端发送POST请求可以使用JavaScript中的fetch API或者XMLHttpRequest对象。以下是使用fetch API发送POST请求的示例代码:
```javascript
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
```
其中,`url`是后端接口地址,`data`是要发送的数据对象,`headers`中指定了请求的Content-Type为application/json,`body`中传递了序列化后的JSON数据。
如果使用XMLHttpRequest对象发送POST请求,代码如下:
```javascript
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.send(JSON.stringify(data));
```
其中,`url`和`data`的含义和fetch API相同,`setRequestHeader`方法指定了请求的Content-Type为application/json,`send`方法传递了序列化后的JSON数据。`onreadystatechange`事件监听请求状态的变化,当请求完成时,会打印响应结果或者错误信息。