Uncaught (In Promise) Typeerror: Failed to Fetch and Cors Error

Uncaught (in promise) TypeError: Failed to fetch and Cors error

Adding mode:'no-cors' to the request header guarantees that no response will be available in the response

Adding a "non standard" header, line 'access-control-allow-origin' will trigger a OPTIONS preflight request, which your server must handle correctly in order for the POST request to even be sent

You're also doing fetch wrong ... fetch returns a "promise" for a Response object which has promise creators for json, text, etc. depending on the content type...

In short, if your server side handles CORS correctly (which from your comment suggests it does) the following should work

function send(){
var myVar = {"id" : 1};
console.log("tuleb siia", document.getElementById('saada').value);
fetch("http://localhost:3000", {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify(myVar)
}).then(function(response) {
return response.json();
}).then(function(muutuja){
document.getElementById('väljund').innerHTML = JSON.stringify(muutuja);
});
}

however, since your code isn't really interested in JSON (it stringifies the object after all) - it's simpler to do

function send(){
var myVar = {"id" : 1};
console.log("tuleb siia", document.getElementById('saada').value);
fetch("http://localhost:3000", {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify(myVar)
}).then(function(response) {
return response.text();
}).then(function(muutuja){
document.getElementById('väljund').innerHTML = muutuja;
});
}

fetch request resulting in error: Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name at HTMLInputElement.<anonymous>

It maybe caused by your header in fetch request.

  1. For X CSRF TOKEN you must type 'X-CSRF-TOKEN' instead of 'X-CSRF TOKEN'
  2. To get a cookie, I suggest this function:
function getCookie(name) {
if (!document.cookie) {
return null;
}

const xsrfCookies = document.cookie.split(';')
.map(c => c.trim())
.filter(c => c.startsWith(name + '='));

if (xsrfCookies.length === 0) {
return null;
}
return decodeURIComponent(xsrfCookies[0].split('=')[1]);
}

response.json() throws "TypeError: Failed to fetch"

This looks like a network error that happened after the response HTTP headers have already been received. In such a situation, the fetch method returns success, but subsequent attempts to access the response body may fail.

I managed to trigger this kind of error with this simple server:

#!/usr/bin/env python3
import http.server
import time

class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.wfile.write(b'HTTP/1.0 200 OK\r\n')
self.wfile.write(b'Content-type: text/html\r\n')
self.wfile.write(b'\r\n')
self.wfile.write(b"""\
<script type="module">
const f = await fetch("/j");
try {
await f.json();
} catch (e) {
alert(e);
}
</script>
""")
return

self.wfile.write(b'HTTP/1.0 200 OK\r\n')
self.wfile.write(b'Content-encoding: gzip\r\n') # bogus
self.wfile.write(b'Content-type: application/json\r\n')
self.wfile.write(b'\r\n')
self.wfile.write(b'[]')


server = http.server.HTTPServer(('127.0.0.1', 31337), Handler)
server.serve_forever()

It introduces a deliberate framing error when serving the JSON response; the headers indicate that gzip compression is employed, but no compression is actually used. When I open http://127.0.0.1:31337/ in Chromium 100.0.4896.127, it displays the following alert:

TypeError: Failed to fetch

Firefox ESR 91.8.0 displays a marginally more helpful:

TypeError: Decoding failed.

The particular framing error demonstrated above is rather contrived, and I doubt it is exactly the kind that the asker experienced. But the fact that it appeared in the middle of the response body is probably at the heart of the described problem.

The specific pair of error types from the question can be triggered by modifying the server thus:

        self.wfile.write(b'HTTP/1.1 200 OK\r\n')
self.wfile.write(b'Content-type: application/json\r\n')
# sic: larger than the actual body length
self.wfile.write(b'Content-length: 2\r\n')
self.wfile.write(b'\r\n')
self.wfile.write(b'[')

This displays the same alert:

TypeError: Failed to fetch

in Chromium (same version), and

AbortError: The operation was aborted.

in Firefox (also same).

As such, a likely cause would be a flaky connection dropped in the middle of receiving the body. The browsers’ errors are not particularly detailed here (and sometimes are downright misleading), so we are resigned to speculate, but this seems like the best guess.



Related Topics



Leave a reply



Submit