fetch POST is returning HTTP 415, while curl goes on fine and returns result(fetch POST 返回 HTTP 415,而 curl 继续正常并返回结果)
问题描述
这就是我的代码的样子
let body = {
authCode: "XXXX",
clientId: "YYYYYY",
clientSecret: "ZZZZZZ"
};
fetch('https://api.myapp.com/oauth/token',{
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
mode: 'no-cors',
body: body
}).then(function(response){
console.log("response: ", response);
}).catch(function(error){
console.log("could not get tokens: ", error);
})
在 Chrome 中,这就是我看到的
In Chrome, this is what I see
我尝试通过 curl 命令
做到这一点,这就是它的样子
I tried to do this by curl command
and this is what it looks like
➜ ~ curl -X POST -H "Content-Type: application/json" -d '{
"authCode": "XXXX",
"clientId": "YYYYY",
"clientSecret": "ZZZZZZZZ"
}' https://api.myapp.com/oauth/token
{"authToken":"e141kjhkwr3432ca9b3d2128385ad91db4cd2:cca6b151-cab4-4de2-81db-9a739a62ae88:23000000"}
我在这里做错了什么?
更新
改成following后,结果还是HTTP 415
After changing it to following, the result is still HTTP 415
fetch('https://api.myapp.com/oauth/token',{
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
mode: 'no-cors',
body: JSON.stringify(body)
}).then(function(response){
console.log("response: ", response);
}).catch(function(error){
console.log("could not get tokens: ", error);
})
有趣的是,我意识到我发送了标题 "Content-Type": "application/json"
而我得到的是 content-type: text/plain
,为什么会这样?
Interestingly, I realized that I sent the header "Content-Type": "application/json"
while what I get back is content-type: text/plain
, why that might be happening?
推荐答案
你必须像这样定义 Accept
和 Content-Type
标头并字符串化你的数据对象
you must define Accept
and Content-Type
headers like that and stringify your data object
const params = {
headers: {
'Accept': "application/json, text/plain, */*",
'Content-Type': "application/json;charset=utf-8"
},
body: JSON.stringify(yourObject),
method: "POST"
};
fetch(url, params)
.then(data => { console.log('data', data)})
.then(res => { console.log('res', res) })
.catch(error => { console.log('error', error) });
这篇关于fetch POST 返回 HTTP 415,而 curl 继续正常并返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:fetch POST 返回 HTTP 415,而 curl 继续正常并返回结果
基础教程推荐
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01