How can I configure CORS for my new API?

0
2
Asked By CuriousCoder42 On

Hey everyone! I'm pretty new to frontend development and I'm trying to figure out a CORS issue that's come up while working on an Angular frontend with a backend REST API. Currently, my frontend is running on app.old.com and the old API is at api.old.com, both of which were on the same site. Now, I'm attempting to move the API to api.new.com, which makes it cross-origin and causes issues with the session cookie for authentication. Since I don't have access to the frontend's domain, I'm wondering if there's a way to allow cross-origin requests from the frontend, and what steps I need to take to make that happen. Can anyone explain it in simple terms?

4 Answers

Answered By CodeNinja77 On

I faced a similar issue using Express. To make `credentials: true` work, I had to specify the origins explicitly since using '*' wouldn't be allowed. I fixed this by using a function to determine the allowed origins. Here's a link to the relevant code: [Code Sample](https://github.com/aymericzip/intlayer/blob/a407f8d9f988eafbf06fb0ec8f6db33abf035a24/apps/backend/src/index.ts#L98)

TechSavant99 -

Awesome, thanks for sharing the code sample!

Answered By DevGuru88 On

Your backend needs to set the `Access-Control-Allow-Origin` to the frontend's origin and also include `Access-Control-Allow-Credentials: true`. Make sure all cookies are set with the right origin, and for any requests, you’ll need to use `fetch(url, { credentials: 'include' })`, or set `crossorigin="use-credentials"` for scripts and images.

CuriousCoder42 -

Thanks for the info! So, I have to use the "credentials" parameter for every request to the API, right? That should be doable since most of our requests go directly to it.

Answered By WebWise78 On

You might want to check out this [MDN article](https://developer.mozilla.org/en-US/docs/Web/HTTP/GUIDES/Cookies) on cookies. It covers a lot of helpful information about how they work with CORS and other issues.

CuriousCoder42 -

I guess I should read through that, but honestly, I'm just trying to get this done without diving into too much documentation right now!

Answered By TechSavant99 On

CORS is something you control on the backend. If you set the proper CORS headers on api.new.com to allow requests from app.old.com, it should work just fine. There's no need to change anything on the frontend for CORS specifically.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.