我正在尝试向json blob api发送POST请求(它是一个简单的api来存储我的JSON文件)。我得到405错误...... 当GOT请求工作正常时,我不知道为什么我不能做POST请求。
有人可以帮帮我吗? https://jsonblob.com/api
const api = "https://jsonblob.com/api/jsonBlob/c30c8afa-6557-11e9-acbe-
61e96b39ce8b"
//it doesn't work
fetch(api, {
method: 'POST',
body: JSON.stringify({
name: 'dean',
login: 'dean',
})
})
.then(response => {
if (response.ok) {
return response.json()
}
throw new Error('Request failed!')
})
.then(jsonResponse => {
console.log(jsonResponse)
})
.catch(error => {
console.log('Request failure: ', error);
});
// get request works fine
fetch(api).then((response) => {
if (response.ok) {
return response.json();
console.log(response)
}
throw new Error('Request failed! ');
})
.then((Jsondata) => {
console.log(Jsondata)
})
.catch(error => {
console.log(error.message)
});
根据该API的文档,您需要在头文件中指定json内容类型,这样可以正常工作:
fetch("https://jsonblob.com/api/jsonBlob", {
method: 'POST',
headers: {
"Content-type": "application/json"
},
body: JSON.stringify({
name: 'dean',
login: 'dean',
})
})
.then(response => {
if (response.ok) {
return response.json()
}
throw new Error('POST Request failed!')
})
.then(jsonResponse => {
console.log(jsonResponse)
})
.catch(error => {
console.log('POST Request failure: ', error);
});
如果您阅读该API的文档,POST请求不会在请求URL中使用blobID - 您还需要添加值为content-type
的application/json
请求标头 - 否则您将收到415错误
它在响应头x-jsonblob
中返回一个Blob ID,因此,要获得稍后使用的Blob ID头,您需要访问头
const api = "https://jsonblob.com/api/jsonBlob"
fetch(api, {
method: 'POST',
body: JSON.stringify({
name: 'dean',
login: 'dean',
}),
// you also have to add this request header for that API
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
if (response.ok) {
const blobID = response.headers.get('x-jsonblob');
console.log(`POST returned a blobID = ${blobID}`);
// return the blobID we can use to fetch the data later
return blobID;
}
throw new Error('POST Request failed!')
}).then(blobID => {
// lets do a GET to see if we get the right data
console.log(`fetch ${api}/${blobID}`);
return fetch(`${api}/${blobID}`)
}).then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('GET Request failed! ');
})
.then((Jsondata) => {
console.log('Result of GET')
console.log(Jsondata)
}).catch(error => {
console.log('Request failure: ', error);
});