Solving CORS Errors in Express.js

Solving CORS Errors in Express.js

While developing a Todo app API and connecting it through the frontend, I encountered a CORS (Cross-Origin Resource Sharing) error. CORS is a mechanism that allows many resources (e.g., fonts, images, scripts) on a web page to be requested from another domain outside the domain from which the resource originated. This can cause issues when developing web applications.

Serving the HTML file from the root directory

One way I solved this issue was by serving the HTML file from the root directory through route.js. This way, both the backend and frontend were running on the same port/URL, which helped prevent CORS errors.

Using the cors package

Another way I effectively solved this issue was by installing the cors package using npm install cors. This package provides an Express middleware that can be used to enable CORS with various options. CORS middleware helps control which origins are allowed to access your server's resources.

Once the cors package was installed, I utilized it as middleware in my Express application by adding app.use(cors()). This essential step allowed my application to handle cross-origin requests and respond to them in a controlled manner.

With the cors middleware in place, even if I opened the HTML file on a live server, I was able to fetch items in a response without encountering any CORS errors.

It’s important to note that while these solutions helped prevent CORS errors in my case, they may not always be applicable or sufficient depending on your specific use case. It’s always a good idea to thoroughly test your application and ensure that it’s working as intended.

Conclusion

In summary, CORS errors can be a common issue when developing web applications. Fortunately, while working with Express.js, you have several effective ways to resolve them. These methods include serving the HTML file from the root directory or employing the cors middleware to manage cross-origin requests more efficiently.

I hope my experience with solving CORS errors while developing a Todo app API with Express.js can be helpful to others facing similar issues. Is there anything else you would like to know?

Code Snippet

Here is an example of how I implemented these solutions in my code:

Index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Todo</title>
    <link rel="stylesheet" href="style.css">
</head>
<script>

    let parsedData = (data) =>{
         console.log(data)
    }

    let callback = (resp) =>{
        resp.json().parsedData();
    }
    let onPress = () =>{
        fetch('http://localhost:3000/todos',{
            method:"Post",
            body: JSON.stringify({
                title:'Gym',
                description:'Yes'
            }),
            headers:{
                "Content-Type":"application/json"
            }
        }).then(callback)
    }
</script>
<body>
    <div class="container">
        <div >
            <label>Todo Title</label>
            <input class="text" type="text" name="" aria-label="">
        </div>
        <div>
            <label>Todo description</label>
            <input class="text" type="text" name="" aria-label="">
        </div>
        <button class="button" onclick="onPress()">Add Todo</button>
    </div>
</body>
</html>

todoServer.js

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const cors = require('cors');

function findIndex(arr,id){
    for(var i of arr){
      if(i.id==id) return arr.indexOf(i);

    }
    return -1;

}

function deleteItemIndex(arr,id){
  var newTodo =[]
  for(var i=0;i<arr.length;i++){
    if(arr[i].id !== id) newTodo.push(arr[i]);
  }
  return newTodo;
}

app.use(bodyParser.json());
app.use(cors());

var todo = []

app.get('/todos',(req,res)=>{
    res.status(200).send(todo);
})

app.get('/todos/:id', (req, res) => {
  var todoIndex = findIndex(todo, parseInt(req.params.id));
  if (todoIndex === -1) {
    res.status(404).send();
  } else {
    res.json(todo[todoIndex]);
  }
});
var counter = 1;
app.post('/todos',(req,res)=>{

  var newTodo = {
    id:counter++,
    title:req.body.title,
    description:req.body.description
  }
  todo.push(newTodo)
  res.status(201).send(newTodo)
})

app.delete('/todos/:id',(req,res)=>{
  const id = parseInt(req.params.id);
  todo = deleteItemIndex(todo, id);

  res.status(200).json(todo);
})

app.put('/todos/:id',(req,res)=>{
  const todoIndex = findIndex(todo, parseInt(req.params.id));
  if (todoIndex === -1) {
    res.status(404).send('Todo item not found.');
  } else {

    if (req.body.title) {
      todo[todoIndex].title = req.body.title
    }
    if (req.body.description) {
      todo[todoIndex].description = req.body.description
    }
    res.status(200).json(todo[todoIndex])
  }
})

app.get('/',(req,res)=>{
  res.sendFile(path.join(__dirname,'index.html'))
})



app.use('*',(req,res)=>{
  res.status(404).send('Route not defined')
})


app.listen(3000,()=>{
  console.log(`Listening at http://localhost:3000`)
})

I hope you found this post useful and informative. If you have any questions or any feedback, feel free to leave a comment below. Happy coding!

Here are my socials

Did you find this article valuable?

Support Mayank's blog by becoming a sponsor. Any amount is appreciated!