day*_*mer 6 javascript curl fetch reactjs fetch-api
这就是我的代码的样子
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);
})
Run Code Online (Sandbox Code Playgroud)
我试着这样做curl command,这就是它的样子
? ~ 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"}
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?
更新
改成follow后,结果还是 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);
})
Run Code Online (Sandbox Code Playgroud)
有趣的是,我意识到我发送了标头,"Content-Type": "application/json"而我返回的是content-type: text/plain,为什么会发生这种情况?
您必须定义这样的标头Accept并对Content-Type数据对象进行字符串化
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) });
Run Code Online (Sandbox Code Playgroud)
fetch()不期望在 处有 JavaScript 对象body。curl命令和fetch()模式不一样。使用body: JSON.stringify(<javascript plain object>)。
注意:
body类型只能是Blob、BufferSource、FormData、URLSearchParams或类型,因此要将对象添加到负载中,您需要对该对象进行字符串化USVString。ReadableStreamJSON
请参阅使用 ReadableStreamReadableStream获取set as value的实现状态body。
| 归档时间: |
|
| 查看次数: |
5366 次 |
| 最近记录: |