Learn CORS In 6 Minutes
Summary
TLDRThis video tutorial explains how to resolve CORS errors in web development. It demonstrates using a simple script and server setup with Express, illustrating how to fix CORS by setting the 'Access-Control-Allow-Origin' header. The video shows how to use the 'cors' library in Express to allow requests from specific origins or any origin. It also covers handling preflight 'OPTIONS' requests for methods like PUT and DELETE, and how to enable the sending of cookies with CORS by setting the 'Access-Control-Allow-Credentials' header.
Takeaways
- 🛠️ CORS stands for Cross-Origin Resource Sharing, and it's a mechanism that uses additional HTTP headers to tell browsers to allow a web application to request resources from a different domain than the one from which the first resource was served.
- 🚫 A common CORS error occurs when a web application tries to fetch data from a server on a different port or domain, and the server does not have the appropriate CORS headers set.
- 🔧 To fix CORS errors, you need to set the 'Access-Control-Allow-Origin' header on the server to specify which origins are allowed to access the server's resources.
- 📚 The script example in the video demonstrates a simple Express server setup that listens on port 3000 and how to configure it to allow requests from a client running on port 5500.
- 🌐 By default, browsers only allow requests to the same origin. If you need to make requests to a different origin, you must specify the allowed origins using the CORS headers.
- 📖 The 'cors' library in Node.js is used to simplify the process of setting CORS headers in Express applications.
- 🔄 When making requests like PUT or DELETE, browsers send an 'OPTIONS' preflight request first to check if the actual request method is allowed by the server.
- 🔄 The 'cors' library allows you to specify which methods are allowed by setting the 'methods' property in the configuration.
- 🍪 If you need to send cookies with a request (include credentials), you must set the 'Access-Control-Allow-Credentials' header to 'true' on the server.
- 🔒 The video provides a comprehensive guide to handling CORS errors and securing web applications by controlling which origins and methods are allowed.
- 🔗 For further reading and related security videos, resources are provided in the video description.
Q & A
What is the main issue the video script is addressing?
-The video script is addressing the issue of CORS (Cross-Origin Resource Sharing) errors that occur when trying to make requests from one origin to another, and how to fix them.
What is CORS and why is it important?
-CORS is a security feature implemented by browsers to restrict web pages from making requests to a different domain than the one that served the web page. It's important for security reasons to prevent malicious websites from making unauthorized requests to other domains.
What is the 'Access-Control-Allow-Origin' header and why is it necessary?
-The 'Access-Control-Allow-Origin' header is an HTTP response header that specifies which origins are permitted to read the response. It is necessary to allow requests from different origins to access the resources on the server.
How does the video demonstrate a CORS error?
-The video demonstrates a CORS error by showing an attempt to fetch data from localhost:3000 from a client running on localhost:5500, resulting in an error message stating that 'No 'Access-Control-Allow-Origin' header is present on the requested resource.'
What library is suggested to handle CORS in an Express server?
-The library suggested to handle CORS in an Express server is 'cors', which can be installed using npm.
What is the purpose of the 'methods' option in the 'cors' library?
-The 'methods' option in the 'cors' library is used to specify an array of HTTP methods that are allowed when making requests from different origins.
What is an 'OPTIONS' request and why is it used?
-An 'OPTIONS' request is a preflight request used by the browser to determine whether the actual request is allowed by the server. It is used for methods like PUT or DELETE to check if the server allows these types of requests.
How can you allow any origin to access your server resources using the 'cors' library?
-You can allow any origin to access your server resources by setting the 'origin' parameter in the 'cors' library to '*'.
What does the 'include' option do when set to 'credentials'?
-The 'include' option, when set to 'credentials', allows the request to include credentials such as cookies, authorization headers, or TLS client certificates.
How do you handle CORS when dealing with cookies?
-To handle CORS with cookies, you need to set the 'Access-Control-Allow-Credentials' header to 'true' on the server side, and include the 'credentials' option in the 'cors' library configuration.
What additional resources are provided for further learning about CORS?
-The video offers links to more security-related videos and a full written version of the video in the description below for further learning about CORS.
Outlines
🛠️ Understanding CORS Errors and Solutions
The paragraph discusses the common issue of CORS (Cross-Origin Resource Sharing) errors in web development. The speaker shares a personal anecdote about frequently encountering these errors and then realizing how to fix them. A simple example is provided where a client-side script tries to fetch data from a server but fails due to a CORS error. The error message indicates that no 'Access-Control-Allow-Origin' header is present on the requested resource. The speaker explains that to fix CORS, one must allow requests from different origins by setting the appropriate headers. A library called 'cors' is introduced to help set these headers in an Express server. Before and after scenarios are discussed, showing how setting the 'Access-Control-Allow-Origin' header allows data to be fetched successfully. The importance of matching the origin in the header to the actual URL making the request is highlighted, and the concept of allowing any origin by using a '*' is also explained.
🔒 Fine-Tuning CORS with Methods and Credentials
This paragraph delves into more advanced CORS configurations, such as controlling which HTTP methods are allowed for cross-origin requests. By default, the 'cors' library allows all methods, but the speaker demonstrates how to restrict this to only 'GET' and 'POST' requests, effectively disallowing 'PUT' requests. The concept of 'OPTIONS' requests, which are preflight requests for 'PUT', 'DELETE', and other non-simple methods, is introduced. The paragraph explains how to respond to these preflight requests by setting the 'Access-Control-Allow-Methods' header. The speaker also covers how to handle cookies and credentials in CORS requests. By default, cookies are not sent with cross-origin requests, but this can be enabled by setting the 'Access-Control-Allow-Credentials' header to 'true'. The paragraph concludes with a mention of additional security-related videos and a written version of the content available in the description, thanking viewers for their time.
Mindmap
Keywords
💡CORS
💡Access-Control-Allow-Origin
💡Express
💡Middleware
💡Origin
💡Preflight Request
💡Options Request
💡Access-Control-Allow-Methods
💡Access-Control-Allow-Credentials
💡Credentials
💡npmi
Highlights
Introduction to CORS errors and how they can be fixed.
Explanation of a simple CORS error example with a script file accessing a server.
Description of the error message indicating the absence of an Access-Control-Allow-Origin header.
Explanation of how Access-Control-Allow-Origin header allows requests from different origins.
Demonstration of setting the header inside Express using the CORS library.
Before and after comparison of CORS error resolution.
Clarification that the default allowed origin is the same origin.
Instructions on specifying allowed origins for cross-origin requests.
Example of fixing CORS by setting the Access-Control-Allow-Origin header to localhost:5500.
Mistake of setting the origin to localhost:5500 instead of 127.0.0.1 and its correction.
Solution to allow any origin by setting the Access-Control-Allow-Origin to a star (*).
Discussion on the limitations of CORS with PUT requests and the need for OPTIONS preflight requests.
Explanation of how to handle OPTIONS preflight requests and the Access-Control-Allow-Methods header.
Demonstration of restricting allowed methods to GET and POST using the CORS library.
Example of how to allow PUT requests by including them in the allowed methods.
Introduction to the concept of sending cookies with CORS and the need for Access-Control-Allow-Credentials header.
Instruction on setting the Access-Control-Allow-Credentials header to true to enable cookie transmission.
Conclusion and summary of the key points about CORS.
Invitation to check out more security-related videos and a written version of the video.
Transcripts
we have technology
it didn't work
[Music]
that used to be me every single time i
ran into a
error until i realized just how easy it
is to fix these errors
so in this video i'm going to show you
everything you need to know about course
so you never have to run into these
types of errors
here's a quick example of a course error
as you can see i just have a simple
script file that's running on my client
it's accessing our server trying to get
some data and it's trying to print that
data out and on our server you can see
we have that data response
we're just using express to set up the
server listening on port 3000
and as you can see when we're trying to
fetch from localhost 5500
to localhost 3000 it's saying that we
cannot fetch that because of course
and it's saying that no access control
allow origin header is present on the
requested resource
and that tells you exactly what you need
to do to fix cores
in order to allow a request to go from
one origin to another so for example
localhost port 5500 to localhost 3000
we need to tell the browser hey we allow
requests to come from other urls
and this is what the access control
allow origin allows us to do it says
where do you allow requests to come from
so our server is telling our client
hey these are the allowed urls that are
able to access us
by default the only allowed url is the
same origin that you come from so we can
make requests from our current origin
but when you're trying to make requests
from a different origin you need to
specify the origins that are allowed
now in order to do this setting of the
header inside of express
we're going to be using a library called
cores to do that and i'll show you the
before and after of what happens
we go to the network tab here we can see
that this data request is being made
and if i just try to come in here and
look at the different headers you can
see that my response headers has nothing
to do with that application
or access control allow origins you can
see it doesn't exist anywhere inside of
here
but if we install that coors library so
we say npmi
cores that's just going to install those
for express there's a million different
ways to do this depending on what
library you're using so if you're using
express it's going to be this course
library
if you're using like python or go
there's going to be their own library or
you can manually set the headers on your
own
but we can just say app.use course and
this is a function
and the first thing we're going to pass
to it is our origin and this is the
origin of the client that we allow
which we know is just localhost 5500
so now if i just make sure that i take
cores and require
that cores library and i save you can
see that
if we go over to our console we're still
getting that request error and that's
because this origin has a value of
localhost 5500
but it's not equal to 127.0.0.1 because
that's our actual url
so let's say 127.0.0.1
now when we save you can see it actually
prints out the data instead of giving us
a course error
if we come in here let's just make sure
we refresh all this open up our data and
you can see we have an access control
allow origin
and it has the actual url that we're
trying to make the request
from so our server is saying hey you
know what if you're coming from this
you know origin then we allow any
request to come up
but let's say this is 5501 that's now a
different origin
so now we're getting that error because
it's saying hey you know what you're not
equal to the allowable origins
also if you want to allow any origin at
all just put a star inside of here
and now if we save this with just a star
you can see that the data is coming
through just fine
and that's because our axis allowed
origins here we come in here our access
control
origin is for every single thing it's
because we have a star here
now this works great when it comes to
things like git and post request this is
going to solve all of your problems for
cores immediately
but if you need to do something like a
put request so if we change this to a
put
and then inside of here we just make our
method
a put method well now we actually have
a different problem that we're going to
run into you'll notice we come in here
let's just
change this back to http
127.0.0.1 port 550
and we click save here and we go to our
console you notice it's printing
everything out just fine
if we go over to our network tab though
and we go to this other section you're
going to notice we also have these
things called
options request and options request is
essentially a preflight request
whenever we do something like a put or
we do something like a delete
we're going to need to do this options
request to make sure we're allowed to do
this put in this delete and if we scroll
down to the response headers you'll see
this access control request method
it's saying hey i want to make a put
request am i allowed to do that
and if you scroll up you're going to see
that we also respond with access control
allowed methods and by default this is
returning everything git head put patch
post delete so it's saying we're allowed
to do all these different types of
things
well inside of course we can actually
change our methods so we can just say
methods
we can pass in an array so we could say
you know what only allow git
and post request no put no none of that
now when i save and i go to the console
we're getting a coors error and that's
because we're trying to use the method
put
but it's not being allowed if we go to
that options you can see that we only
are allowing git
and post and that doesn't match the put
that we're trying to actually do a
request
on we can use this method to fine tune
what different things we allow
other urls to actually do by default
it's allowing everything with this
course library but we could say you know
only do git and post and no puts are
going to be allowed
or we could remove that and now if this
will actually successfully work because
put
is being allowed now the final thing
that i want to talk about with course is
going to be how you can actually send up
cookies because by
default cookies are blocked if we come
into here we can just say that we want
to pass
in credentials and we just say include
that's going to include our credentials
in the request and you notice we
immediately get
cores issues again because we don't have
an access control allow credentials
header so we need to set this access
control allow credentials header
on the server this is as easy as just
saying with i'm sorry credentials
and setting that to true that is going
to set this access control allow
credentials
and if we go to our network and we go
and we scroll down here you'll see
access control allow credentials is set
to true that's all there is to cores
if you're interested in more security
related videos they're going to be
linked over here and a full written
version of this video is also linked
down in the description below
thank you very much for watching and
have a good day
Ver Más Videos Relacionados
#26: Connect React with NodeJS & MongoDB | Stored Registration Form Data in Database in MERN
Quick Tutorial - Users and Permissions in SQL Server
MERN quiz creator app Part 2: Creating a database, Creating a basic api, adding JWT authentication.
Express JS #5 - Post Requests
ESP32 Servo Motor Web Server with Arduino IDE
Build a Microservice with Go #1 - Getting Started
5.0 / 5 (0 votes)