gpt4 book ai didi

javascript - 使用 Fetch API 发布 XML

转载 作者:数据小太阳 更新时间:2023-10-29 01:57:04 24 4
gpt4 key购买 nike

我正在尝试使用 Fetch API 来处理 XML 数据的 POST,以避免 XmlHttpRequest 的跨源问题。我面临的问题是,尽管将我的 Content-Type 设置为“text/xml”(在这种情况下这是唯一受支持的内容类型 header ),但我的请求的内容类型正在重置为 text/plain,导致 HTTP 状态为415 来自请求的内容。

这是我的获取函数:

    function doFetch(Content)
{
return fetch(
URL, { method: 'POST',
mode: 'no-cors',
headers: new Headers(
{'Content-Type': 'text/xml; charset=utf-8',
'Accept': '*/*',
'Accept-Language': 'en-GB',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'Keep-alive',
'Content-Length': Content.length
}),
body: Content
});
}

内容是一串 XML 数据。

这是实际使用的 header :

    Content-Length:1537
content-type:text/plain;charset=UTF-8

只是想知道我正在尝试做的事情是否可行,以及我做错了什么? (我是网络开发的新手)。

谢谢!

最佳答案

因为您正在设置 mode: 'no-cors' (为什么?...)对于请求,浏览器不允许您设置除 CORS-safelisted request-headers 以外的任何请求 header 。 .参见 the spec requirements :

…if guard is "request-no-cors" and name/value is not a CORS-safelisted request-header, return.

设置Content-Type: text/xml; charset=utf-8使其不再是 CORS 安全列表请求 header ; Content-Type如果其值为 application/x-www-form-urlencoded,则它只是一个 CORS 安全列表请求 header , multipart/form-data , 或 text/plain .

所以这里的解决方案的开始是不使用 mode: 'no-cors' .

唯一通常设置 mode: 'no-cors' 有意义的情况如果你使用 Service Worker 来缓存响应——因为对于 mode: 'no-cors'请求,浏览器不会让您的脚本访问响应的任何属性,因此您可以使用它做的唯一有用的事情就是缓存它。

I'm trying to use Fetch API to handle POST of XML data to avoid cross-origin issues with XmlHttpRequest.

Fetch API 遵循与 XHR 相同的跨域请求模型,因此不清楚您使用 Fetch API 试图避免哪些跨域问题......

关于javascript - 使用 Fetch API 发布 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42222937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com