π¦ Browser APIs - Data Handling
The Story of the Magical Translator
Imagine you have a friend who lives far away. You want to send them a box of toys. But hereβs the catch: the mail truck only carries paper notes, not real toys!
So what do you do?
- You write down what each toy looks like on paper π
- Send the paper through the mail π¬
- Your friend reads the paper and rebuilds the toys! π§Έ
This is exactly how computers send data to each other!
π§ββοΈ JSON.parse and JSON.stringify
The Two Magic Spells
Think of these as two magical spells:
| Spell | What It Does |
|---|---|
JSON.stringify() |
Turns toys into paper notes |
JSON.parse() |
Turns paper notes back into toys |
π JSON.stringify - Pack Your Toys
When you want to send data somewhere (like to a server), you need to turn it into text first.
const myToys = {
name: "Teddy Bear",
color: "brown",
age: 5
};
// Turn object into text
const paperNote = JSON.stringify(myToys);
console.log(paperNote);
// '{"name":"Teddy Bear","color":"brown","age":5}'
What happened?
- Your JavaScript object (the toy) became a string of text
- Now it can travel through the internet! π
π¦ JSON.parse - Unpack Your Toys
When you receive data from somewhere, it arrives as text. You need to turn it back into a real object!
const receivedNote = '{"name":"Robot","color":"silver"}';
// Turn text back into object
const myNewToy = JSON.parse(receivedNote);
console.log(myNewToy.name);
// "Robot"
console.log(myNewToy.color);
// "silver"
Magic! π© The text became a real JavaScript object you can use!
β οΈ Watch Out for Errors!
If the paper note is messy (bad JSON), the spell fails:
try {
const badNote = "this is not JSON";
JSON.parse(badNote); // π₯ Error!
} catch (error) {
console.log("Oops! Bad note!");
}
Pro Tip: Always wrap JSON.parse() in a try-catch block!
π URL and URLSearchParams
Whatβs a URL?
A URL is like a home address for websites. Just like your house has a street number, city, and country, a URL has parts too!
https://toystore.com/search?toy=bear&color=brown
β β β β
β β β βββ The questions you're asking
β β βββ The room you want (path)
β βββ The house name (domain)
βββ How to travel there (protocol)
π The URL Object
JavaScript gives you a special tool to read and change URLs easily:
const myURL = new URL(
"https://toystore.com/search?toy=bear&color=brown"
);
console.log(myURL.hostname);
// "toystore.com"
console.log(myURL.pathname);
// "/search"
console.log(myURL.search);
// "?toy=bear&color=brown"
π URLSearchParams - The Question Helper
The part after ? in a URL contains search parameters. Think of them as questions you ask the website.
// Create from existing URL
const url = new URL(
"https://shop.com?item=ball&size=large"
);
const params = url.searchParams;
// Read a value
console.log(params.get("item"));
// "ball"
console.log(params.get("size"));
// "large"
β Adding and Changing Parameters
const params = new URLSearchParams();
// Add new questions
params.append("color", "red");
params.append("price", "10");
console.log(params.toString());
// "color=red&price=10"
// Change a value
params.set("color", "blue");
console.log(params.toString());
// "color=blue&price=10"
π Loop Through All Parameters
const params = new URLSearchParams(
"name=teddy&type=bear&size=small"
);
for (const [key, value] of params) {
console.log(`${key}: ${value}`);
}
// name: teddy
// type: bear
// size: small
π CORS Basics
The Security Guard Story
Imagine your browser is a playground. The website youβre visiting is one kid in the playground.
Now, this kid wants to borrow toys from a kid in another playground across the street.
But wait! Thereβs a security guard π‘οΈ who checks:
βDoes the other playground allow sharing toys?β
This security guard is called CORS (Cross-Origin Resource Sharing).
What is βOriginβ?
An origin is made of three parts:
https://toystore.com:443
β β β
β β βββ Port number
β βββ Domain name
βββ Protocol
Same Origin = All three parts match Different Origin = Any part is different
π« The CORS Error
When you try to fetch data from a different origin without permission:
// You're on: https://mysite.com
// Trying to fetch from: https://api.othersite.com
fetch("https://api.othersite.com/data")
.then(response => response.json())
.catch(error => {
// π₯ CORS Error!
console.log("Blocked by CORS!");
});
β How CORS Works
The server (other playground) must say βYes, you can share!β
graph TD A["Your Browser"] -->|1. Can I have data?| B["Other Server"] B -->|2. Checks CORS rules| B B -->|3. Yes! Here's data| A
The server adds special headers to allow sharing:
Access-Control-Allow-Origin: https://mysite.com
Or to allow everyone:
Access-Control-Allow-Origin: *
π§ͺ Preflight Requests
For βdangerousβ requests (like POST with JSON), the browser first sends a test question:
graph TD A["Browser"] -->|1. OPTIONS: Can I send data?| B["Server"] B -->|2. Yes, you may!| A A -->|3. POST: Here's my data| B B -->|4. Here's the response| A
This test is called a preflight request.
π‘ Simple vs Complex Requests
| Simple Request | Complex Request |
|---|---|
| GET, HEAD, POST | PUT, DELETE, PATCH |
| Standard headers | Custom headers |
| No preflight | Needs preflight |
π οΈ Common CORS Solutions
If you control the server:
- Add
Access-Control-Allow-Originheader
If you DONβT control the server:
- Use a proxy server (your own server talks to theirs)
- Ask the API owner to enable CORS
π― Quick Summary
| Concept | What It Does | Example |
|---|---|---|
JSON.stringify() |
Object β Text | JSON.stringify({a:1}) |
JSON.parse() |
Text β Object | JSON.parse('{"a":1}') |
URL |
Read URL parts | new URL(link).hostname |
URLSearchParams |
Handle ?query=params | params.get("key") |
| CORS | Security for cross-origin requests | Server must allow it |
π You Did It!
Now you understand:
- β How to pack and unpack data with JSON
- β How to read and build URLs like a pro
- β Why CORS exists and how it protects you
Youβre ready to handle data like a web wizard! π§ββοΈβ¨
