[Web Development] Fix CORS Error On Server Side
You met several times CORS Error when you developed your web application with rest-ful api.
In this post, I will let you know how to solve CORS error in server side but unfortunately, I do not introduce fix it in front end(client side) in this post.
Morden web browsers DO NOT ALLOWS to call any apis from the other origin server. That is why you saw the error.
This is simple web application in code pen
<HTML>
1 2 3 | <button id="get">Get Posts</botton> <button id="post">Create a Post</botton> | cs |
<JS>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | const getButton = document.getElementById("get") const postButton = document.getElementById("post") getButton.addEventListener('click', () => { fetch('http://localhost:8080/feed/posts') .then(res => res.json()) .then(resData => console.log(resData)) .catch(err => console.log(err)); }) postButton.addEventListener('click', () => { fetch('http://localhost:8080/feed/post', { method:"POST", body: JSON.stringify({ title: "A CodePen Post", content: "Created via Codepen" }), headers: { 'Content-Type': 'application/json' } }) .then(res => res.json()) .then(resData => console.log(resData)) .catch(err => console.log(err)); }) | cs |
Normally you cannot call the api and you can see the error like that
For resolve this issue, you should add some headers on your api.
on you app.js file you can add this lines
1 2 3 4 5 6 | app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); next(); }) | csT |
This middle ware setting let approve to use the api on the other server. Of course, you can allow specific methods for instance, GET, PUT, and etc...
Now you can check the api calling is working well.