Search code examples
node.jsreactjsherokucorsbackend

CORS Node.js in chrome browser


I am using Heroku and netlify to host

https://n-blogcode.netlify.app/

Now I m using cors in backend and it needed to be switched on using a chrome extension on my pc for the cards section to work.

But not everyone will know to enable cors access through extension to see my website. So how do I make it so everyone can directly see it


Solution

  • Use the npm cors package in your nodejs program, and place your netlify origin on the allowed list.

    Something like this might work.

    const express = require('express')
    const cors = require('cors')
    const app = express()
    
    var corsOptions = {
      origin: 'https://n-blogcode.netlify.app'
    }
    
    ...
    
    app.use(cors(corsOptions))           //cors for all routes
    app.options('*', cors())             //cors for preflight requests
    

    This causes your nodejs program to include the appropriate CORS headers in its responses to requests from your html / js code hosted on netlify.

    You definitely don't want to require a web extension for your users. If you do, you won't have many users. :-)