. Advertisement .
..3..
. Advertisement .
..4..
Numerous websites utilize the lightweight, object-oriented programming language JavaScript (js) to script their webpages. It is an interpreted, complete programming language that enables dynamic interactivity on websites when used with an HTML document. TypeError – Failed to fetch and CORS in JavaScript is a common error that shows up in many ways. Read on this article to find the best way to fix it.
How Does The Error TypeError – Failed to fetch and CORS in JavaScript Occur?
When you run your program, you easily get the following error:
TypeError - Failed to fetch and CORS
There are several causes of the error:
- The fetch() method has been called with an incomplete or incorrect URL.
- The proper CORS headers are not being returned by the server you are requesting.
- The fetch() method has received an invalid way or set of headers.
- The URL contains an incorrect protocol.
Let’s follow this example:
async function getUser() {
try {
const feedback = await fetch('https://sample.com/document');
if (!feedback.ok) {
throw new Error(`Error! status: ${feedback.status}`);
}
const termination = await feedback.json();
return termination;
} catch (err) {
console.log(err);
}
}
getUser();
We received two exceptions because the url we gave to the fetch() method is not correct:
- CORS – “No ‘Access-Control-Allow-Origin’ header is present on the requested resource”.
- “TypeError: Failed to fetch”
If you’re using the fetch method, ensure that the URL you supply it is accurate and complete. You have to do the following requirements :
- If you’re testing on localhost without an SSL certificate, let’s put the protocol in there, for example https:// or http://.
- The path needs to be accurate. For instance, /articles.
- The HTTP method for the definite path must be accurate.
- You would receive an error if you misspelled any of the configuration, such as a property in the headers object or the HTTP method.
How To Solve The Error TypeError – Failed to fetch and CORS in JavaScript?
Approach 1: Make sure to supply the appropriate configuration to the fetch method
You have to make sure to supply the appropriate configuration to the fetch method, including the URL, HTTP method, and headers, to resolve the “TypeError – Failed to fetch and CORS” error. Additionally, ensure the server you request is setting the appropriate CORS headers with the response.
async function getUser() {
try {
const feedback = await fetch('https://randomuser.me/api/', {
method: 'GET',
headers: {
accept: 'application/json',
},
});
if (!feedback.ok) {
throw new Error(`Error! status: ${feedback.status}`);
}
const termination = await feedback.json();
return termination;
} catch (err) {
console.log(err);
}
}
getUser();
Make sure the body is supplied to the JSON.stringify() method in the call to get if you’re doing a POST, PUT, or PATCH request. If the configuration you supply to the fetch method is accurate, verify that your server is returning the proper CORS headers. The server must set the following CORS headers along with the response:
your domain is following, for example http://localhost:3000
Access-Control-Allow-Origin: http://example.com
Access-Control-Allow-Methods: POST, PUT, PATCH, GET, DELETE, OPTIONS
Access-Control-Allow-Headers: Origin, X-Api-Key, X-Requested-With, Content-Type, Accept, Authorization
Open the Network tab in your browser, click on the request, and examine if your server is setting these CORS-related headers. Depending on your use case, you may need to adjust the settings.
Here are the headers:
- Which origins are permitted to make requests to the server are specified by the Access-Control-Allow-Origin header.
- The HTTP methods that sources are enabled to use when sending requests to the server are specified by the Access-Control-Allow-Methods header.
- HTTP headers the origins that are permitted to use while sending requests to the server are used in the Access-Control-Allow-Headers field.
Try using the *
(asterisk) symbol as the origin in the case the CORS options don’t function and see whether it resolves the issue. Any origin on the internet is permitted to access the server when the Access-Control-Allow-Origin header is set to an asterisk *
.
Although you want to focus on this in production, it’s a helpful tool for debugging.
Approach 2: Use the following syntax
Excepting the above solution, there is another solution for you to solve the error “TypeError – Failed to fetch and CORS” in JavaScript. It is using the following syntax:
await fetch(url, {
mode: 'no-cors'
})
This approach is very simple, but it works flawlessly for you. Let’s apply it to get your desired results.
Conclusion
This post discussed about the causes and the solutions of TypeError – Failed to fetch and CORS in JavaScript. We hope you enjoy our post. We would appreciate it if you share your thoughts with us via the comment box below. If you still have any other questions about fixing this syntax error, please leave a comment below. Thank you for reading!
Read more
→ How to Fix “TypeError: unsupported operand type(s) for /: list and int”
Leave a comment