Learn CORS In 6 Minutes

Web Dev Simplified
22 May 202106:06

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

00:00

πŸ› οΈ 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.

05:01

πŸ”’ 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

CORS stands for Cross-Origin Resource Sharing, a security feature implemented by browsers to restrict web applications from making requests to a domain different from the one that served the web page. In the video, CORS errors are a central issue, as they prevent the client-side script from accessing data from the server due to the lack of an 'Access-Control-Allow-Origin' header. The script attempts to fetch data from a different port (localhost 5500 to localhost 3000), which triggers a CORS error until the header is properly set.

πŸ’‘Access-Control-Allow-Origin

This is an HTTP header used to tell the browser which origins are permitted to make requests to the server. In the video, setting this header is crucial for resolving CORS errors. The script shows how, by default, the header is not present, leading to errors, but once it's set to allow requests from 'localhost 5500', the data can be fetched successfully.

πŸ’‘Express

Express is a popular web application framework for Node.js. In the video, Express is used to set up the server that listens on port 3000. The script demonstrates how to configure CORS on an Express server by using the 'cors' middleware to handle the 'Access-Control-Allow-Origin' header.

πŸ’‘Middleware

Middleware in Express.js is a function that has access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The video uses the 'cors' middleware to add the necessary CORS headers to the server's responses, thus enabling cross-origin requests.

πŸ’‘Origin

In the context of web development, the origin is a combination of protocol, hostname, and port. The video explains that by default, browsers only allow requests to the same origin. CORS errors occur when requests are made to a different origin, and the video demonstrates how to specify allowed origins to resolve these errors.

πŸ’‘Preflight Request

A preflight request is a type of request that browsers send before making the actual request, particularly for non-simple requests like PUT or DELETE. The video explains that these requests are made to check if the server allows the desired method. The 'Access-Control-Allow-Methods' header is used to specify which methods are allowed.

πŸ’‘Options Request

An OPTIONS request is a type of preflight request that browsers send to determine if the server allows a particular type of request. In the video, the script shows how the server responds to an OPTIONS request with 'Access-Control-Allow-Methods' to specify the allowed HTTP methods.

πŸ’‘Access-Control-Allow-Methods

This HTTP header is used to specify the methods allowed when accessing a resource in response to a preflight request. The video demonstrates how to set this header using the 'cors' middleware to allow methods like GET, POST, PUT, PATCH, and DELETE.

πŸ’‘Access-Control-Allow-Credentials

This header indicates whether the response to the request can be exposed when the credentials flag is true. The video explains that by default, cookies are blocked in cross-origin requests, but setting 'Access-Control-Allow-Credentials' to true allows cookies to be included.

πŸ’‘Credentials

Credentials in web requests refer to cookies, authorization headers, or TLS client certificates. The video discusses how to include credentials in cross-origin requests by setting the 'Access-Control-Allow-Credentials' header to true, which is necessary when cookies or other credentials need to be sent with the request.

πŸ’‘npmi

npmi is a command used in Node.js environments to install packages. In the video, 'npmi cors' is used to install the 'cors' middleware package, which is then used to handle CORS headers on the Express server.

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

play00:00

we have technology

play00:07

it didn't work

play00:08

[Music]

play00:11

that used to be me every single time i

play00:14

ran into a

play00:15

error until i realized just how easy it

play00:17

is to fix these errors

play00:19

so in this video i'm going to show you

play00:20

everything you need to know about course

play00:22

so you never have to run into these

play00:23

types of errors

play00:24

here's a quick example of a course error

play00:27

as you can see i just have a simple

play00:28

script file that's running on my client

play00:30

it's accessing our server trying to get

play00:32

some data and it's trying to print that

play00:34

data out and on our server you can see

play00:35

we have that data response

play00:37

we're just using express to set up the

play00:38

server listening on port 3000

play00:41

and as you can see when we're trying to

play00:42

fetch from localhost 5500

play00:45

to localhost 3000 it's saying that we

play00:47

cannot fetch that because of course

play00:49

and it's saying that no access control

play00:51

allow origin header is present on the

play00:52

requested resource

play00:54

and that tells you exactly what you need

play00:56

to do to fix cores

play00:57

in order to allow a request to go from

play01:00

one origin to another so for example

play01:02

localhost port 5500 to localhost 3000

play01:05

we need to tell the browser hey we allow

play01:08

requests to come from other urls

play01:10

and this is what the access control

play01:12

allow origin allows us to do it says

play01:14

where do you allow requests to come from

play01:16

so our server is telling our client

play01:18

hey these are the allowed urls that are

play01:20

able to access us

play01:21

by default the only allowed url is the

play01:24

same origin that you come from so we can

play01:25

make requests from our current origin

play01:27

but when you're trying to make requests

play01:28

from a different origin you need to

play01:30

specify the origins that are allowed

play01:32

now in order to do this setting of the

play01:34

header inside of express

play01:35

we're going to be using a library called

play01:36

cores to do that and i'll show you the

play01:38

before and after of what happens

play01:39

we go to the network tab here we can see

play01:41

that this data request is being made

play01:43

and if i just try to come in here and

play01:44

look at the different headers you can

play01:46

see that my response headers has nothing

play01:48

to do with that application

play01:50

or access control allow origins you can

play01:52

see it doesn't exist anywhere inside of

play01:54

here

play01:54

but if we install that coors library so

play01:56

we say npmi

play01:57

cores that's just going to install those

play01:59

for express there's a million different

play02:01

ways to do this depending on what

play02:02

library you're using so if you're using

play02:03

express it's going to be this course

play02:05

library

play02:05

if you're using like python or go

play02:07

there's going to be their own library or

play02:08

you can manually set the headers on your

play02:10

own

play02:10

but we can just say app.use course and

play02:13

this is a function

play02:14

and the first thing we're going to pass

play02:15

to it is our origin and this is the

play02:17

origin of the client that we allow

play02:19

which we know is just localhost 5500

play02:23

so now if i just make sure that i take

play02:26

cores and require

play02:27

that cores library and i save you can

play02:30

see that

play02:31

if we go over to our console we're still

play02:32

getting that request error and that's

play02:34

because this origin has a value of

play02:35

localhost 5500

play02:37

but it's not equal to 127.0.0.1 because

play02:40

that's our actual url

play02:42

so let's say 127.0.0.1

play02:45

now when we save you can see it actually

play02:46

prints out the data instead of giving us

play02:48

a course error

play02:49

if we come in here let's just make sure

play02:50

we refresh all this open up our data and

play02:52

you can see we have an access control

play02:54

allow origin

play02:55

and it has the actual url that we're

play02:57

trying to make the request

play02:58

from so our server is saying hey you

play03:00

know what if you're coming from this

play03:01

you know origin then we allow any

play03:03

request to come up

play03:05

but let's say this is 5501 that's now a

play03:08

different origin

play03:09

so now we're getting that error because

play03:10

it's saying hey you know what you're not

play03:11

equal to the allowable origins

play03:13

also if you want to allow any origin at

play03:15

all just put a star inside of here

play03:18

and now if we save this with just a star

play03:21

you can see that the data is coming

play03:22

through just fine

play03:23

and that's because our axis allowed

play03:24

origins here we come in here our access

play03:27

control

play03:27

origin is for every single thing it's

play03:29

because we have a star here

play03:31

now this works great when it comes to

play03:32

things like git and post request this is

play03:34

going to solve all of your problems for

play03:36

cores immediately

play03:37

but if you need to do something like a

play03:38

put request so if we change this to a

play03:40

put

play03:41

and then inside of here we just make our

play03:44

method

play03:46

a put method well now we actually have

play03:50

a different problem that we're going to

play03:51

run into you'll notice we come in here

play03:52

let's just

play03:53

change this back to http

play03:58

127.0.0.1 port 550

play04:01

and we click save here and we go to our

play04:03

console you notice it's printing

play04:04

everything out just fine

play04:05

if we go over to our network tab though

play04:07

and we go to this other section you're

play04:08

going to notice we also have these

play04:10

things called

play04:10

options request and options request is

play04:12

essentially a preflight request

play04:14

whenever we do something like a put or

play04:16

we do something like a delete

play04:17

we're going to need to do this options

play04:19

request to make sure we're allowed to do

play04:20

this put in this delete and if we scroll

play04:22

down to the response headers you'll see

play04:24

this access control request method

play04:26

it's saying hey i want to make a put

play04:27

request am i allowed to do that

play04:29

and if you scroll up you're going to see

play04:31

that we also respond with access control

play04:32

allowed methods and by default this is

play04:34

returning everything git head put patch

play04:36

post delete so it's saying we're allowed

play04:37

to do all these different types of

play04:38

things

play04:39

well inside of course we can actually

play04:41

change our methods so we can just say

play04:43

methods

play04:44

we can pass in an array so we could say

play04:45

you know what only allow git

play04:47

and post request no put no none of that

play04:50

now when i save and i go to the console

play04:51

we're getting a coors error and that's

play04:53

because we're trying to use the method

play04:54

put

play04:55

but it's not being allowed if we go to

play04:56

that options you can see that we only

play04:58

are allowing git

play04:59

and post and that doesn't match the put

play05:01

that we're trying to actually do a

play05:02

request

play05:03

on we can use this method to fine tune

play05:05

what different things we allow

play05:07

other urls to actually do by default

play05:09

it's allowing everything with this

play05:10

course library but we could say you know

play05:12

only do git and post and no puts are

play05:14

going to be allowed

play05:14

or we could remove that and now if this

play05:16

will actually successfully work because

play05:18

put

play05:18

is being allowed now the final thing

play05:20

that i want to talk about with course is

play05:21

going to be how you can actually send up

play05:23

cookies because by

play05:24

default cookies are blocked if we come

play05:26

into here we can just say that we want

play05:27

to pass

play05:28

in credentials and we just say include

play05:30

that's going to include our credentials

play05:31

in the request and you notice we

play05:33

immediately get

play05:33

cores issues again because we don't have

play05:35

an access control allow credentials

play05:37

header so we need to set this access

play05:39

control allow credentials header

play05:40

on the server this is as easy as just

play05:42

saying with i'm sorry credentials

play05:44

and setting that to true that is going

play05:46

to set this access control allow

play05:47

credentials

play05:48

and if we go to our network and we go

play05:50

and we scroll down here you'll see

play05:52

access control allow credentials is set

play05:54

to true that's all there is to cores

play05:56

if you're interested in more security

play05:58

related videos they're going to be

play05:59

linked over here and a full written

play06:00

version of this video is also linked

play06:02

down in the description below

play06:03

thank you very much for watching and

play06:04

have a good day

Rate This
β˜…
β˜…
β˜…
β˜…
β˜…

5.0 / 5 (0 votes)

Related Tags
CORSCross-OriginWeb DevelopmentError FixingExpress.jsHTTP RequestsSecurityJavaScriptTutorialTech Tips