无标题时无法获取POST

hto*_*hko 28 javascript cors fetch-api

提出这样的要求:

return fetch(
            'http://localhost:8000/login',
            {   method: 'POST',
                headers: new Headers(
                   {"Content-Type": "application/json",
                    "Accept":"application/json"}
                ),

                body: JSON.stringify(
                   {'name': 'Tom', 'password': 'Soyer'}
                )
             }
           ).then( response => { console.log(response);})
            .catch(err => console.log(err))
Run Code Online (Sandbox Code Playgroud)

请求使用OPTIONS方法运行而不是POST.仅在添加模式时:'no-cors'请求变为POST:

return fetch(
            'http://localhost:8000/login',
            {   method: 'POST',
                mode: 'no-cors',
                headers: new Headers(
                   {"Content-Type": "application/json",
                    "Accept":"application/json"}
                ),
                body: JSON.stringify(
                   {'name': 'Tom', 'password': 'Soyer'}
                )
             }
           ).then( response => { console.log(response);})
            .catch(err => console.log(err))
Run Code Online (Sandbox Code Playgroud)

但响应不好(即使网络响应状态为200):{type:"opaque",url:"",status:0,ok:false,statusText:""...}我想是因为

Content-Type标头唯一允许的值是:application/x-www-form-urlencoded multipart/form-data text/plain

这里描述https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

是否有任何方式可以使用fetch生成POST json数据?

Asa*_*din 35

Content-Type您发送的自定义标头会导致您的请求被预检,这意味着将在实际POST请求之前发送包含有关即将发送的POST请求的一些元数据的OPTIONS 请求.

您的服务器需要准备好处理此OPTIONS请求.您尚未指定服务器的编写内容,但例如,您可以注册一个拦截所有"OPTIONS"请求的中间件,设置Access-Control-Allow-Origin: *Access-Control-Allow-Headers: Content-Type标头,并以200响应.

如果您可以使用'Content-Type':'text/plain'标题发出请求,那将解决您的问题.或者你可以使用完全绕过XHR的东西,比如JSONP.


sdc*_*sdc 11

使用时non-cors,所有标头必须是有效的simple-headerscontent-type符合简单标头的标头的唯一有效值是:

headers: [
  ['Content-Type', 'application/x-www-form-urlencoded'],
  ['Content-Type', 'multipart/form-data'],
  ['Content-Type', 'text/plain'],
]
Run Code Online (Sandbox Code Playgroud)

意外情况的例外:

headers: [
  ['Content-Type', 'application/csp-report'],
  ['Content-Type', 'application/expect-ct-report+json'],
  ['Content-Type', 'application/xss-auditor-report'],
  ['Content-Type', 'application/ocsp-request'],
]
Run Code Online (Sandbox Code Playgroud)