Using Fetch API to POST XML

不羁岁月 提交于 2020-04-13 05:09:06

问题


I'm trying to use Fetch API to handle POST of XML data to avoid cross-origin issues with XmlHttpRequest. The issue I face is that despite setting my Content-Type to 'text/xml' (which is the only supported content-type header in this case) my request's content-type is being reset to text/plain resulting in a HTTP status of 415 from the requested content.

Here is my fetch function:

    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
           });
    }

Content is a string of XML data.

And this is the header which is actually being used:

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

Just wondering if what I'm trying to do is possible, and if it is what I'm doing wrong? (I'm kind of new to web-development).

Thanks!


回答1:


Because you’re setting mode: 'no-cors' (why?…) for the request, browsers won’t allow you to set any request headers other than CORS-safelisted request-headers. See the spec requirements:

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

Setting Content-Type: text/xml; charset=utf-8 makes it no longer a CORS-safelisted request-header; Content-Type is only a CORS-safelisted request-header if its value is application/x-www-form-urlencoded, multipart/form-data, or text/plain.

So the start of a solution here is to not use mode: 'no-cors'.

The only case where it usually makes sense to set mode: 'no-cors' is if you’re using Service Workers for caching responses—because for a mode: 'no-cors' request, browsers won’t let your script access any properties of the response, so the only useful thing you can do with it is cache it.

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

The Fetch API follows the same cross-origin request model as XHR, so it’s unclear what cross-origin issues you’d be attempting to avoid by using the Fetch API…




回答2:


Cors or cross origin access means that you can't transfer data between 2 servers on different ip's or even ports if you are not explicitly specify that with the Allow-Cross-Origin-Acess tag inside you're response header. Sending from the client this tag won't do. It has to be in the header of the response.



来源:https://stackoverflow.com/questions/42222937/using-fetch-api-to-post-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!