Data Handling

Back

Loading concept...

πŸ“¦ 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?

  1. You write down what each toy looks like on paper πŸ“
  2. Send the paper through the mail πŸ“¬
  3. 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-Origin header

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! πŸ§™β€β™‚οΈβœ¨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.