How to use CORS in backend (NodeJs and ExpressJs). Best way to set headers tutorial.(2022)

Coding image from unsplash free photos
How to use CORS in backend (NodeJs and ExpressJs). Best way to set headers tutorial.(2022)

In this blog you will know how to use CORS in backend and best ways to set headers in backend and secure your backend. CORS is most useful package which you can install in your project from NPM and YARN. best way to set options of cors in nodejs and any other languages.

What is CORS?

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which browsers make a "preflight" request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request.

How to Install CORS in your project?

To install CORS in your project, you can use NPM or YARN. if you don't know these package manager. you can google both packages to know how to use it.

Installing CORS using NPM package manager:

 $ npm install cors 

Installing CORS using YARN package manager:
 
 $ yarn add cors

After successfully installing. create server.js file in your backend folder and create server with express.

In your server.js file you can add this. and add the cors options which is described below.

CORS keys:
1) origin: it accept only string value or array string[] value. here you enter your sites url which you want to accept request from. you can add multiple url.
 
a. String only: 
 app.use(
    cors({
        origin: "your client side url" // https://youtube.com
        })
     ) 
 b. Array with value string[]
app.use(
    cors({
        origin: ["your client site url", "your second url"] // ["https://youtube.com", "http://localhost:3000"]
        })
     ) 
 
2) methods: methods is optional if you want add only certain methods that can client site make.  
here you can add request methods like GET, POST, PUT, DELETE, etc
 
3) credentials (Important): this is the important in cors to send cookie from your client site you can add with credential: true if not you will get error you never understand what happens to your code

you can check out other options but they are optional and not very important.
  const express = require("express");
  const app = express();
  const port = process.env.PORT || 5000;
 // require your cors library
  const cors = require("cors"); 
 app.use(
  cors({
    origin: "http://localhost:3000", // add here your client site url
    methods: ["GET", "POST", "PUT", "DELETE"], // this optional you can add your own
    credentials: true, // this is important if you want to send cookie from client site
  })
  
  app.listen(port, ()=> console.log(`Server is running on port : ${port}`);
); 
Now run your code with your client side and make request. Make sure your backend is running perfectly.
 
// output will be your result
 

Conclusion:

CORS is a very tricky library but its very important to understand if you want make request or Rest API. you can setup your cors options to  create requests from your site. If you like please add a comment on this blog it will help us to grow in google search engine we share our courses for free. thank you and follow us

 

Written by:

Awesh Choudhary

3 Comments

  1. Thanks for your reference best solution of cors found on google

    ReplyDelete
  2. Best tutorial for cors thank you

    ReplyDelete
Post a Comment
Previous Post Next Post