DEV Community

Charles πŸ›°
Charles πŸ›°

Posted on

How to solve fu***** cors?

I will document how to solve cors in a few steps.

Imagine you have an api where you want to POST or GET things but when you post or get something you receive a CORS error policy, if you want a deep understanding of cors i will leave this link.

Imagine you have an api at localhost:9000 and all the different routes related to it.

We will have to create a proxy

mkdir proxy
cd proxy
npm init -y
npm i express
npm i http-proxy-middleware nodemon --save-dev
touch index.js
Enter fullscreen mode Exit fullscreen mode

Now that we have installed our dependencies we can go to the code.

Inside package.json add the following

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },
Enter fullscreen mode Exit fullscreen mode

Now inside index.js we add the following code

const express = require('express');
const app = express()
const { createProxyMiddleware } = require('http-proxy-middleware');

app.use('/', createProxyMiddleware({target: 'http://localhost:9000', changeOrigin:true}))

app.listen(5000)
Enter fullscreen mode Exit fullscreen mode

This way we will be able to make request to the url localhost:5000 and since it is a proxy we will be able to make request to the routes that the original route has for instance the main route is localhost:9000/api/users, but now in order to not get cors policy we will have to make a call to localhost:5000/api/users and it should work just fine.

Thanks.

Top comments (0)