DEV Community

Cover image for Handling CORS in Axios and Socket.io
Abhishek shah
Abhishek shah

Posted on • Updated on

Handling CORS in Axios and Socket.io

What is CORS??

CORS stand for Cross-Origin Resource Sharing. It's a way for the server to check if the client the server is communicating with is actually a permitted client to use the server. Before the browsers send the actual request for any operation the client sends a preflight request with a header where Origin is set to its base URL and the server replies with a Access-Control-Allow-Origin in response header.
If it's value is a wildcard('*') or the base URL matches the Origin set in the request header only then the actual request is made else you get a CORS error. This has been shown in the picture below especially focusing on the Origin values in the request header and Access-Control-Allow-Origin in the response header.

Header exchanges after a request is made

If you are getting a CORS error go to inspect mode by pressing F12 and go to network and see in the header of any file , you will find a request and response header. You can add other headers to it at CORS

Now Lets see how to handle the CORS error if you are using

  1. Axios You can use CORS npm package
var express = require('express')
var cors = require('cors')
var app = express()

var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Here you can directly do an app(cors(corsOptions)) before the routers or you can add cors(corsOptions) in the (req,res,next) part.

2 Socket.io

In socket.io you have to add cors while creating io.

const io = require("socket.io")(server, {
  cors: {
    origin: "https://example.com",
    methods: ["GET", "POST"]
  }
})
Enter fullscreen mode Exit fullscreen mode

If you have anything to add do comment and share your views.

Top comments (0)