简体   繁体   中英

Fetch vs. XMLHttpRequest reliability

I'm not able to find out, why XMLHttpRequest works and using the fetch or axiom does not work. The endpoint is constant. Here is the code to compare ... XMLHttpRequest actually returns the text, fetch does not return anything

var r = new XMLHttpRequest()
    r.open('GET', 'http://localhost:1337/ticks', true)
    r.onreadystatechange = function () {
        if (r.readyState !== 4 || r.status !== 200) {
            return
        }
    }
    r.send()

    fetch('http://localhost:1337/ticks', {
            method: 'GET',
            mode: 'no-cors'
            }).then(function (response) {
                return response.text()
            }).then(function (text) {
                console.log(text)
    }).catch(function (error) {
    })

Don't do this:

 mode: 'no-cors' 

It tells fetch that you want to make the request (to tell the server something) but don't want to read the response (which might be forbidden by the Same Origin Policy). This setting lets you do that without throwing the error you would normally get. Since you said you don't want to read the response, fetch doesn't try to make the response available to you.

Removing the mode: 'no-cors' actually brings the body of the response to life. Just in case somebody has the same problem... So there is still a question why fetch works this way, cause the no-cors is pretty much useless, when you get no response body with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM