我正在尝试对 JSON blob API 执行 POST 请求(这是一个用于存储 JSON 文件的简单 API),但我收到了 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 错误
它在响应标头中返回 Blob ID
x-jsonblob
,因此,要获取 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);
});