fetch POST返回HTTP 415,而curl正常进行并返回结果 [英] fetch POST is returning HTTP 415, while curl goes on fine and returns result

查看:410
本文介绍了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"}

我在这里做什么错了?

更新

将其更改为以下内容后,结果仍然是 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:文本/纯文本,为什么会发生这种情况?

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?

< a href = https://i.stack.imgur.com/Ym6D4.png rel = noreferrer>

推荐答案

fetch()不会在 body 处出现JavaScript对象。 curl 命令和 fetch()模式不相同。使用 body:JSON.stringify(< javascript纯对象>)

fetch() does not expect a JavaScript object at body. curl command and fetch() pattern are not the same. Use body: JSON.stringify(<javascript plain object>).

请求


注意: body 类型只能是 Blob BufferSource FormData
URLSearchParams USVString ReadableStream 类型,因此要将
a JSON 对象添加到有效负载中,您需要对该对象进行字符串化。

Note: The body type can only be a Blob, BufferSource, FormData, URLSearchParams, USVString or ReadableStream type, so for adding a JSON object to the payload you need to stringify that object.

有关<$的实施状态,请参见使用ReadableStream获取 c $ c> ReadableStream 设置为 body 的值。

See Fetch with ReadableStream for status of implementation of ReadableStream set as value for body.

这篇关于fetch POST返回HTTP 415,而curl正常进行并返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆