Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 19, 2021 11:06 am GMT

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'))    }  }}

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"]  }})

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


Original Link: https://dev.to/shahiscoding/handling-cors-in-axions-and-socket-io-1l0a

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To