Тёмный

JavaScript Fetch with Request and Headers Objects 

Steve Griffith - Prof3ssorSt3v3
Подписаться 102 тыс.
Просмотров 65 тыс.
50% 1

Going beyond just the basics of using fetch for AJAX calls, this video talks about the finer details of using custom Request objects, custom Header objects, as well as some of the methods that are available to deal with the response.
A brief discussion of using the Chrome Dev Tools to monitor the network requests is included.
Code GIST: gist.github.co...
List of Forbidden HTTP Headers: developer.mozi...
Request Object Reference: developer.mozi...
Headers Object Reference: developer.mozi...

Опубликовано:

 

20 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 98   
@craigjohnson8279
@craigjohnson8279 6 лет назад
This is the best tutorial that I've seen on the Fetch API. Other people only talked about the basic GET request but Steve takes it to another level. I now understand Headers, Methods, and Modes. Thanks for sharing the knowledge.
@Kliamframe
@Kliamframe 6 лет назад
Really like your relaxing and in depth way on explaining. Helped me a lot. Thank you!
@zoverlvx8094
@zoverlvx8094 6 лет назад
You're like the Bob Ross of programming. Subscribed!
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 6 лет назад
Now THAT is a compliment!
@zoverlvx8094
@zoverlvx8094 6 лет назад
My pleasure!
@rotrose7531
@rotrose7531 4 года назад
Second round, most comprehensive explanation on Headers() and Request() I found by far. Thank you.
@Muhyideen869
@Muhyideen869 2 года назад
Thank you!! I was stuck because I kept receiving a response in XML format, I was pulling my hair out trying to figure out how to request JSON lol. Very clear explanations, thanks a bunch
@martyoconnor7211
@martyoconnor7211 6 лет назад
THANK YOU! Your videos are succinct and extremely useful.
@ReV157
@ReV157 2 года назад
Hey man, thanks a lot. Your video really helped me. I was having error and difficulty understanding this type of request, but your video certainly helped me in what I needed and I learned how to actually use fetch. A thousand thanks.
@herrschaufele7210
@herrschaufele7210 4 года назад
Thank you for your very easy to understand tutorials
@kamaboko1
@kamaboko1 6 лет назад
I've watched a number of fetch api tuts on RU-vid. Many are good and get the job done, but your layout is superior. I will unashamedly use this as a template. Thanks.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 6 лет назад
kamaboko1 glad I could help
@mitchell4217
@mitchell4217 3 года назад
Wow, didn't even realize new headers() and new Request() were even a thing. Makes it a lot easier.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 года назад
You can also use new Body( ) and new FormData( ) or when you get into Service Workers new Request( )
@mitchell4217
@mitchell4217 3 года назад
@@SteveGriffith-Prof3ssorSt3v3 Are these all stand-alone methods? Or do they only work with the fetch() method?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 года назад
@@mitchell4217 they can all be used independently but they are not of much use unless you are sending and receiving things from the server... meaning fetch
@mitchell4217
@mitchell4217 3 года назад
@@SteveGriffith-Prof3ssorSt3v3 I was thinking more broadly, like would it work with AJAX, Axios, or whatever your method of choice.
@rumbly438b7
@rumbly438b7 7 лет назад
Thanks. Quite an impressive library of videos. I was going to request a vid on using headers with fetch but here it is.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 7 лет назад
Glad I could help.
@behindthescenex
@behindthescenex 6 лет назад
Mr. Steve thank you so much for your lecture and your easy to catch explanation. Sir, if i may can i request a tutor about using fetch for the oAuth system ? Im currently want to get some data of song titles from the spotify web api, and its hard to get the data from the api because i need to get token first within the oAuth system. Ive read the docs and still i cant figure it out. Waiting for your reply sir. Once again thank you so much ! :)
@Kliamframe
@Kliamframe 6 лет назад
Did you use fetch to make your request? ;)
@imay6262
@imay6262 2 года назад
Your voice sounds as the actor who gives his voice to Lex Luttor in the Latinamerican spanish version XD... nice video by the way!
@blayke602
@blayke602 5 лет назад
Hey steve, I've been an avid watcher of your js vid series. I recently stared learning about web development through your channel in hopes of becoming a frond end dev someday. I just want to know, in which instances am I required to setup my custom request/ header like what you did on this tutorial, compared to just regularly using xmlHttprequest or basic fetch?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 5 лет назад
I stopped using XMLHttpRequest a few years ago. fetch has better security and eventually XHR will be dropped by the browsers. The only time you have to use the Request object or the Header object are when you need to customize things - need an Authentication header? Send form data to the server? need special settings to deal with CORS?
@blayke602
@blayke602 5 лет назад
Steve Griffith thank you very much!, i'll keep that in mind
@kezioevan1030
@kezioevan1030 2 года назад
Thankyou bro, your video saved my problem :)
@raycoustum
@raycoustum 4 года назад
I couldnt understand very much, but i finished my practice. Thnks
@DOUBLE0SEVUN
@DOUBLE0SEVUN 5 лет назад
How would I add a bearer token to the fetch request? I have an api_key that is required in the request and I don't where to place it to properly get the json data back. When I make the request it says that I am unauthorized.
@lowencholawliet5383
@lowencholawliet5383 5 лет назад
Same here. Can't add bearer token. Im using axios api. :/
@zhenghaohe4727
@zhenghaohe4727 4 года назад
A question: at 8:00 you said you will get the file back but then based on the cors policy that will tell me whether or not I'm allowed to actually view that data. So does that mean, the stuff that's requested cross origins will arrive to the client's browser no matter what. Depends on the cors policy that the server set, the client's javascript might or might not have access to those stuff?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 года назад
CORS does a preflight request to test the origin and look for the appropriate headers. It will block some things outright. However, there is also CORB cross origin read blocking, which will prevent the loading into memory of things that came back to the server. I didnt get into the full discussion of CORS and CORB. That's a whole other video in itself.
@CarlosSantana-mf9tl
@CarlosSantana-mf9tl 4 года назад
No hablo inglés pero explicas tan bien que hasta te entendí en español jajaja xd
@angladephil
@angladephil 5 лет назад
Thank you for this very didactic, well structured and explained tutorial ! In addition, as a Frenchman, I appreciate that your English accent is very understandable... Technically speaking, I guess I may "simulate" or "implement" the example URI you provide with a local node.js server, am I right ? Thank you.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 5 лет назад
Thanks. And Yes. You can do that.
@MichalRutz
@MichalRutz 4 года назад
Excellent job! thank you so much!
@juanpumpkinpie6550
@juanpumpkinpie6550 4 года назад
stunning explanation Steve! There is a group videos of Fetch API topics?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 года назад
Yes. I have a playlist about AJAX - ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-7EKebb4VUYQ.html
@poderaccionsocialcolombia9847
Hello Steve, thank you for sharing with us valuable content, with patience and language easy to understand for us, the beginners. I am trying to run this for getting data from coinmarketcap API, using the key and url respectively. In VS Code everything is ok, but when inspecting element in the browser, it throws the Error. I already used the mode: 'no-cors', but not getting anywhere. Any help would be appreciated.
@SteveGriffith-Prof3ssorSt3v3
If you are requesting data from a domain that is different than where your html came from then you can't use no-cors. It is literally a different origin. It is a cors request.
@poderaccionsocialcolombia9847
@@SteveGriffith-Prof3ssorSt3v3 thank you very much for the response. Reading in more detail that app, coinmarketcap has restrictions to access its APIs throughout javascript. So I´m getting into node js to acquiring the data needed. I am checking out your videos about this 😃
@saadowain3511
@saadowain3511 3 года назад
You are a gift from God.
@ke6944
@ke6944 3 года назад
Professor, should I learn HTTP before Async JavaScript?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 года назад
HTTP is not really something that you need to study and learn if you understand the idea of what it is. When a browser and a server talk to each other they do this through Requests and Responses. HTTP is the format of those requests and responses. There are HTTP Methods that are used for the requests. GET - the default. A READ request for some resource. POST - you are uploading data to create some new resource (think submitting a registration form) PUT/PATCH - updating a resource DELETE - deleting a resource HEAD - you just want the headers for the resource as the response. All requests and responses are made up of a HEAD and a BODY. The BODY is the uploaded data or attached file. The HEAD are all the settings and meta info about the request or response. If you understand that, you have enough to do any fetch / ajax call. I assume that is what you are asking about based on the video where you added the comment. Asynchronous Javascript is something else. - ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-Q-Zmc0E0GYY.html - fetch and promises are a small part of that.
@ke6944
@ke6944 3 года назад
@@SteveGriffith-Prof3ssorSt3v3 Thanks
@ashishmangla221
@ashishmangla221 4 года назад
I am trying to fetch data using headers but I am getting following error has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 года назад
That means that the server is not sending you the access-control-allow-origin header. Without that your browser is not allowed to use the data
@ashishmangla221
@ashishmangla221 4 года назад
@@SteveGriffith-Prof3ssorSt3v3 but i can get data in postman. Can I share my code with you
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 года назад
@@ashishmangla221 Postman does not have the same CORS restrictions that browsers do.
@ashishmangla221
@ashishmangla221 4 года назад
@@SteveGriffith-Prof3ssorSt3v3 one more question when I am sending api key in url I am able to get data. And when I am sending key in header I am getting error. Why it's so. I am trying to fetch data from coincap market
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 года назад
@@ashishmangla221 the way you have to send the data depends on how the API is configured. They might want it in the url path, or in a header, or a cookie, or the query string, or form data or JSON string in the body of the request. Every API is different. You need to read their documentation to see what they expect.
@KhanhTran-yx2zd
@KhanhTran-yx2zd 4 года назад
The way you explain things is magical, thank you! While playing around with the fetch API I ran into an issue that I'm not sure how to get around. I made a fetch request to a URI that simply returns the webpage at that URI. I then proceeded to try and set a cookie on the Response object returned by the fetch request, but noticed that the headers property of the Response object is read-only. How would one accomplish the task of setting a cookie for the Response object returned by fetch? I was looking to try and set a cookie on the client when they receive the webpage returned by fetch.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 года назад
You can't modify the Response object. It is created by the server and sent to the fetch. All the properties in the Response are read only. The Request object is the one that you can assemble to send with the fetch call. However, cookies can be created in the browser with document.cookie. If your fetch Request is being sent to the same domain as the webpage then the cookie will be included by default. The Request object has a property called credentials. By default, its value is 'same-origin', which means if the domain is the same as the webpage then include cookies. The other values are 'omit' and 'include' which describe what to do with the cookies from document.cookie.
@KhanhTran-yx2zd
@KhanhTran-yx2zd 4 года назад
@@SteveGriffith-Prof3ssorSt3v3 Perfectly explained, thank you! I feel much more relieved now that I feel like I'm absorbing the material. So if the fetch request is to a resource of the same domain, I can use document.cookie to set a cookie that will be sent with the fetch request. However, I'm guessing that this isn't possible from the server-side only, since document.cookie needs to be set from the client-side? Since Response objects are read-only, it seems that the only way to use cookies alongside a fetch request is by setting it up from the client-side first? I was hoping to do everything from the server-side. I looked into creating my own Response object so that I can create my own headers, but at the same time using the contents contained within the Response object returned by the fetch request (in this case, it contains a webpage). Although, I have no idea if you can construct a new Response object using contents of another Response object as its body... Any insight would be appreciated, but don't feel obligated. You've help me understand the fundamentals, so thanks again!
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 года назад
@@KhanhTran-yx2zd The Server-side code is what builds and sends the Response Object. It can set cookies that will be received and set in the browser.
@waleedsharif618
@waleedsharif618 4 года назад
Could you possibly help(or send some video link) me with one thing, i need to retrieve data(using javascript or react hooks) from the API , API has end points( i have url link for them) and both end points require an API-key. API key is set in the http-request header with key #####. Access-Control-Allow-Origin is set to any origin (`#`). If you possibly could help me or send some tutorial video helping retrieve data knowing this kind of information, would appreciate. Have learned a lot from your hard work, thank you for that !
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 года назад
Here are a few videos that should help ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-MvNT0Jis-3k.html ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-Ju5FGcyifEA.html ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-zswi0cPMxsU.html
@waleedsharif618
@waleedsharif618 4 года назад
Steve Griffith thank you for answering, i have two more question regarding this. 1: since i know the value of x-api-key which is set in http-request header should i use setRequestHeader()?. 2: i dont have access to other side (regarding access-control-allow-origin) so i cannot add those files you mentioned in video but if its set to any origin already do i need to ?
@isniphsi7843
@isniphsi7843 Год назад
Wath if i dont set the header? Or can i set the accept header to accept all ? In my case i want to send leage flies via stream
@isniphsi7843
@isniphsi7843 Год назад
Accept header to accept all is */* Right ? Good Video thx
@SteveGriffith-Prof3ssorSt3v3
The accept header in a request is a suggestion for the server. You list your preference for file types to be returned from the server, in response to your specific file request, IF there are multiple options. Eg: json vs xml or jpg vs png. Headers have default values that are set by the browser when you make your request. Not all headers are needed with every request. The browser will add the ones that are needed. If you are using web sockets and sending a stream that is different than the HTTP headers that I am covering in this video.
@bellemcky
@bellemcky 6 лет назад
Thanks so much Steve!
@rotrose7531
@rotrose7531 4 года назад
Legend, Thank you!
@durgani
@durgani 5 лет назад
Thanks, you've helped me!!!
@kabakiAntony
@kabakiAntony 4 года назад
I have a backend that has a login route that returns a token on success, how do I ensure that the next page after login uses the token , rather how do I send the token in when I am getting the next page after login to ensure that I only get to that page when I am logged in and with a verified token
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 года назад
Typically you would put the token into sessionStorage which would be accessible by all pages on the website. Access to the page itself is not something that the token allows or prevents on the client side if we are using sessionStorage. We would use JS to get the token from sessionStorage and then make a fetch request for the DATA with the token in the Authorization header. I really don't care if someone downloads the HTML shell of a page. I do care if they want to access private data on that page. If you are building a website with multiple HTML files you could put the token into a cookie which would automatically be sent with each request. Then the code on the server would decide whether or not the page is allowed to be sent to the browser request.
@kabakiAntony
@kabakiAntony 4 года назад
@@SteveGriffith-Prof3ssorSt3v3 Thanks a lot let me puch the code with that in mind.
@deependrasinghshekhawat2856
@deependrasinghshekhawat2856 3 года назад
thanks again :)
@Sejira
@Sejira 3 года назад
There is a way to make a specif Http request and save one or all http request headers? Request, not response. Thanks
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 года назад
Every time you make a fetch call you are returned a Response Object. The fetch call itself that you are sending has a set of Request headers. You define this in the options object for the fetch all. The headers can be passed in as a regular JavaScript object. There are many headers that you are NOT allowed to set though. See the lists of forbidden ones here - developer.mozilla.org/en-US/docs/Web/API/Headers
@Sejira
@Sejira 3 года назад
@@SteveGriffith-Prof3ssorSt3v3 I asked for security reason and test. You says "you define this", so if i make a fetch request with var = Request.Headers, i have to set the headers after. My question is about possibility of get headers like Authorization with XSS vulnerability. So i have js inside my page(who is in restricted area with basic auth, i open my page, js do a fetch request in the same page(im just testing) and then save the Authorization value header for request, with the previusly saved value in my browser. I don't want to define anything.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 года назад
@@Sejira fetch( url, options) .then( ) .then( ) .catch( ) Inside the options object you can define your own headers. The browser will add its own headers regardless of what you do. There is a list of forbidden Request headers that you are not allowed to set via JavaScript. There is a list of headers that you cannot access from the Response object too. To set the headers in the Request... let abc = new Headers(); abc.append('x-my-header', 'my header value'); let options = { headers: abc } OR let options = { headers: { 'x-my-header': 'my header value' } } Both approaches work. The value of options.headers can come from anywhere. The source of your values is the security risk. Never let users provide these values. The browser will look at the values you use BEFORE the fetch( ) is sent. It will merge its own values before it is sent.
@Sejira
@Sejira 3 года назад
@@SteveGriffith-Prof3ssorSt3v3 Thanks for reply again :) Any chance to contact you privately? Twitter, mail or what you have. "The browser will add its own headers regardless of what you do" Okay but, i want to do a fetch request with fetch (url) and after define a variable with inside the previously header request. So, im in restricted area with Auth header saved in my browser, because i have put credentials before ofc. var myRequest = new Request('192.168.1.129/index.html'); var myHeaders = myRequest.headers; var specificheader = myHeaders.get('User-Agent'); // just for try one var myRequest2 = new Request('192.168.1.129/'+ specificheader); fetch(myRequest).then(fetch(myRequest2)); OR var myRequest = new Request('192.168.1.129/index.html'); var myHeaders = myRequest.headers; var myRequest2 = new Request('192.168.1.129/'+ myHeaders); fetch(myRequest).then(fetch(myRequest2)); The myheaders variable is always still empty when i try to send it away. "The browser will add its own headers regardless of what you do" But how can i save them in to a variable?
@romeojoseph766
@romeojoseph766 Год назад
May I know where you get this much knowledge?
@SteveGriffith-Prof3ssorSt3v3
I started web development back in 1996... so I've had a long time to accumulate information. 😉
@romeojoseph766
@romeojoseph766 Год назад
@@SteveGriffith-Prof3ssorSt3v3 kinda jealous of you hehehe
@nathanbrunetti9852
@nathanbrunetti9852 6 лет назад
What would you do if your using an API that requires you to pass a userName and API key?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 6 лет назад
It would really depend on how the API wants those passed - as a queryString parameter, as a FormData field, or as a basic authorization header. I have videos on those topics too. Fetch / AJAX Playlist - ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-7EKebb4VUYQ.html
@nathanbrunetti9852
@nathanbrunetti9852 6 лет назад
Hey Steve, thanks for the fast reply. I believe its looking for a basic authorization header. I will check out this video and let you know if it worked. Thanks.
@nathanbrunetti9852
@nathanbrunetti9852 6 лет назад
Hey Steve I watch this video (ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-MvNT0Jis-3k.html) and I feel like I'm very close, but I'm getting this error in the console (Failed to load MY_URL_HERE: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin '127.0.0.1:49724' is therefore not allowed access.) Any other suggestions would be greatly appreciated. Thanks.
@CindyExPlayer
@CindyExPlayer 5 лет назад
How put parameters in method post??
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 5 лет назад
You put them in a FormData object and then set the value of the body property of the Request object to that FormData object. ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-9mhyo1wQGeI.html
@scottvu8366
@scottvu8366 5 лет назад
Thank you ❤️
@giorgibatsiashvili4270
@giorgibatsiashvili4270 6 лет назад
awesome
@vikasprasad7565
@vikasprasad7565 4 года назад
i am getting cors issue
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 года назад
This should help - ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-zswi0cPMxsU.html
@anirudhkhanna3615
@anirudhkhanna3615 6 лет назад
Thanks a lot. Very Helpful video.
@thedev6368
@thedev6368 3 года назад
request is depreciated now, shouldn't use it if watching presently
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 года назад
What are you talking about specifically? Request is a core part of how fetch works - developer.mozilla.org/en-US/docs/Web/API/Request/Request Request, Headers, Response, Body, and URL - these are the parts that make up every request and response.
@mukeshshah2204
@mukeshshah2204 7 лет назад
Nice video
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 7 лет назад
Thanks! Don't forget to subscribe so you get notified as I add more videos each week.
@sajidhussain6712
@sajidhussain6712 4 года назад
CORS_ORIGIN_ALLOW_ALL=True
@mohammadesmaielemadi8480
@mohammadesmaielemadi8480 4 года назад
TY, excellent video.
Далее
Ten Steps to Mastering the Fetch API
2:19:52
Просмотров 47 тыс.
HTTP Headers & Methods - Rest APIs In Depth
33:37
Просмотров 2,9 тыс.
Fetch Headers and Why They Matter
15:58
Просмотров 9 тыс.
JSON and AJAX Tutorial: With Real Examples
40:45
Просмотров 1,8 млн
Sending AJAX Form Data to the Server with fetch
14:54
1.1: fetch() - Working With Data & APIs in JavaScript
15:39
Sending JavaScript Http Requests with XMLHttpRequest
18:53
This Is Why Python Data Classes Are Awesome
22:19
Просмотров 810 тыс.
Getting Started with indexedDB
26:18
Просмотров 44 тыс.