DEV Community

Charles 🛰
Charles 🛰

Posted on

2 2

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs