js发送post请求 json格式数据
时间: 2023-03-26 09:03:22 浏览: 123
可以使用XMLHttpRequest对象或者fetch API发送POST请求,同时将JSON格式的数据作为请求体发送。例如:
```
var xhr = new XMLHttpRequest();
xhr.open('POST', 'url', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
var data = {key1: 'value1', key2: 'value2'};
xhr.send(JSON.stringify(data));
```
或者使用fetch API:
```
fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({key1: 'value1', key2: 'value2'})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
```
相关问题
js发送post请求json格式
以下是一个示例代码,使用JavaScript发送POST请求并传递JSON格式的数据:
```javascript
const data = {
name: "John",
age: 30,
city: "New York"
};
fetch('/api/users', {
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));
```
在这里,我们使用了`fetch`函数来发送POST请求。我们需要传递两个参数- URL和一个对象。
在对象中,我们指定了以下属性:
- `method`: 请求的方法,这里是POST。
- `headers`: 包含请求头的对象,我们设置了Content-Type为application/json。
- `body`: 请求体,我们将JavaScript对象转换为JSON字符串后传递。
在请求完成后,我们使用`.then()`方法来解析响应。我们首先将响应转换为JSON格式,然后将其打印到控制台中。
如果请求失败,则会在控制台中记录错误。
vue请求如何发送json格式数据
在Vue中发送JSON格式的请求可以使用axios库来实现,具体步骤如下:
1. 安装 axios 库
```
npm install axios --save
```
2. 在 Vue 组件中使用 axios 发送请求
```javascript
import axios from 'axios'
export default {
methods: {
sendData() {
const data = {
name: 'John',
age: 30
}
axios.post('/api/data', data)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
}
}
}
```
在上面的例子中,我们使用 axios.post() 方法发送 POST 请求,并将 data 对象作为第二个参数传递给该方法。axios 库会自动将 data 对象转换为 JSON 格式并设置请求头为 'application/json'。
请注意,如果你需要发送 GET 请求,则需要使用 axios.get() 方法,同时将参数作为第二个参数传递。如果你需要发送 PUT 请求,则需要使用 axios.put() 方法,以此类推。
如果你需要在请求头中添加其他信息,例如授权信息等,请使用 axios 的请求拦截器。例如:
```javascript
import axios from 'axios'
axios.interceptors.request.use((config) => {
config.headers.Authorization = 'Bearer ' + localStorage.getItem('token')
return config
})
export default {
methods: {
sendData() {
const data = {
name: 'John',
age: 30
}
axios.post('/api/data', data)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
}
}
}
```
在上面的例子中,我们使用 axios 的请求拦截器在请求头中添加了授权信息。