Why am I getting the error 400, when the fetch url is ok?

640
February 13, 2020, at 05:00 AM

If I access the link in the browser, it returns the expected result most of the times.

Meaning: Sometimes, when I access the url in the browser I get the 400 error (say, 1 in 7 times), but it's fine after a browser refresh.

Also sometimes when it's called with fetch(), it throws the 400 error.

I don't understand why and how to fix it.

I am testing the file in the browser, locally.

Should I write the code to fetch again upon failure? Is that a good practice?

Example code:

fetch('https://my-url/some-code').then(res => res.json()).then(res => res).catch(error => console.log(error));
// randomNum iteration: expected result
// randomNum iteration: expected result
// randomNum iteration: 400 error
Answer 1

Should I write the code to fetch again upon failure? Is that a good practice?

Ideally you wouldn't want to call a second request, because there is most likely an underlying problem on your server that is resulting in this response being a 400 code. I don't see any problems with your current fetch request. If you can't fix your endpoint problem however, then just do the second fetch again. If it is only happening 1/7 times then you're only increasing the average workload time by 12.5%, which isn't a huge deal unless this is a heavily used application.

If a refresh on your browser is needed sometimes however, I'd pursue a bit more troubleshooting to make sure it really is your backend. Does the problem not go away unless you refresh? If so, can you access it correctly by opening a separate instance while the other is in need of a refresh? That would point to front-end possibly.

Answer 2
fetch('https://my-url/some-code').then(res => res.json()).(error => console.log(error); 

removing the next then() and remove the error which is not in the ( )

READ ALSO
Dot notation in React imports

Dot notation in React imports

I have been seeing many react frameworks recommend dot notation while importinge

470
Inject JavaScript files inside Templates or HTML with webpack

Inject JavaScript files inside Templates or HTML with webpack

Let's say I have a server (Node & Express for example) which serves HTML pages to clients based on templates files (as pug, ejs, handlebars, twig, marko

509
How do I override a JQuery (Datatable RowGroup) library function?

How do I override a JQuery (Datatable RowGroup) library function?

I'm rather new to Javascript, and the scoping syntax definitely confuses me when looking at open source libraries especially when it has a lot of advanced concepts like closure, anonymous functions, etcThe Jquery Datatables RowGroup is a a bit buggy with Responsiveness,...

506
How to fix 401 after attempt to override existing POST?

How to fix 401 after attempt to override existing POST?

I'm receiving 401 error when trying to override existing POST with new dataIt throws 401

3241