Używamy cookies, żeby zwiększyć Twoje doświadczenia na stronie
CodeWorlds

POST, PUT, DELETE - Wysylanie danych do serwera

Do tej pory pobieralismy dane z serwera (GET). Teraz nauczymy sie wysyłać dane do serwera - tworzyć nowe zasoby (POST), aktualizowac istniejace (PUT) i usuwać (DELETE). To jak wysyłanie rozkazow z naszego statku kosmicznego do Centrum Dowodzenia.

Metody HTTP

Każda metoda HTTP ma swoje przeznaczenie:

1// GET    - Pobierz dane (domyslna metoda fetch)
2// POST   - Utworz nowy zasob
3// PUT    - Zaktualizuj cały zasob
4// PATCH  - Zaktualizuj część zasobu
5// DELETE - Usun zasob

Zapytanie POST - tworzenie nowych zasobow

Aby wysłać dane do serwera, musimy skonfigurowac obiekt opcji

fetch()
:

1async function createMission(missionData) {
2  const response = await fetch(
3    'https://api.space-center.com/missions',
4    {
5      method: 'POST',
6      headers: {
7        'Content-Type': 'application/json',
8      },
9      body: JSON.stringify(missionData),
10    }
11  );
12
13  if (!response.ok) {
14    throw new Error('Nie udalo sie utworzyc misji');
15  }
16
17  const newMission = await response.json();
18  return newMission;
19}
20
21// Uzycie:
22const mission = await createMission({
23  name: 'Alpha Centauri Exploration',
24  crew: ['Kapitan Nova', 'Dr. Astro'],
25  priority: 'high',
26});

Naglowki zapytania (Headers)

Naglowek

Content-Type
informuje serwer, w jakim formacie wysyłamy dane:

1// JSON - najczęściej używany format
2headers: {
3  'Content-Type': 'application/json',
4}
5
6// Dane formularza
7headers: {
8  'Content-Type': 'application/x-www-form-urlencoded',
9}
10
11// Autoryzacja - token dostępu
12headers: {
13  'Content-Type': 'application/json',
14  'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIs...',
15}

Formularz z POST w React

1import React, { useState } from 'react';
2
3function MissionForm() {
4  const [name, setName] = useState('');
5  const [destination, setDestination] = useState('');
6  const [submitting, setSubmitting] = useState(false);
7  const [result, setResult] = useState(null);
8  const [error, setError] = useState(null);
9
10  const handleSubmit = async (e) => {
11    e.preventDefault();
12    setSubmitting(true);
13    setError(null);
14
15    try {
16      const response = await fetch(
17        'https://api.space-center.com/missions',
18        {
19          method: 'POST',
20          headers: { 'Content-Type': 'application/json' },
21          body: JSON.stringify({ name, destination }),
22        }
23      );
24
25      if (!response.ok) {
26        throw new Error(\`Blad: \${response.status}\`);
27      }
28
29      const data = await response.json();
30      setResult(data);
31      setName('');
32      setDestination('');
33    } catch (err) {
34      setError(err.message);
35    } finally {
36      setSubmitting(false);
37    }
38  };
39
40  return (
41    <form onSubmit={handleSubmit}>
42      <input
43        value={name}
44        onChange={e => setName(e.target.value)}
45        placeholder="Nazwa misji"
46        required
47      />
48      <input
49        value={destination}
50        onChange={e => setDestination(e.target.value)}
51        placeholder="Cel podrozy"
52        required
53      />
54      <button type="submit" disabled={submitting}>
55        {submitting ? 'Tworzenie misji...' : 'Utworz misje'}
56      </button>
57
58      {error && <p className="error">{error}</p>}
59      {result && (
60        <p className="success">
61          Misja "{result.name}" utworzona! ID: {result.id}
62        </p>
63      )}
64    </form>
65  );
66}

PUT - Aktualizacja zasobu

1async function updateMission(id, updatedData) {
2  const response = await fetch(
3    \`https://api.space-center.com/missions/\${id}\`,
4    {
5      method: 'PUT',
6      headers: { 'Content-Type': 'application/json' },
7      body: JSON.stringify(updatedData),
8    }
9  );
10
11  if (!response.ok) {
12    throw new Error('Aktualizacja nie powiodla sie');
13  }
14
15  return await response.json();
16}

DELETE - Usuwanie zasobu

1async function deleteMission(id) {
2  const response = await fetch(
3    \`https://api.space-center.com/missions/\${id}\`,
4    {
5      method: 'DELETE',
6    }
7  );
8
9  if (!response.ok) {
10    throw new Error('Usuwanie nie powiodlo sie');
11  }
12
13  // DELETE często zwraca 204 No Content (brak body)
14  return response.status === 204;
15}
16
17// W komponencie React
18function MissionItem({ mission, onDelete }) {
19  const [deleting, setDeleting] = useState(false);
20
21  const handleDelete = async () => {
22    if (!window.confirm('Na pewno usunac misje?')) return;
23
24    setDeleting(true);
25    try {
26      await deleteMission(mission.id);
27      onDelete(mission.id);
28    } catch (err) {
29      alert('Blad: ' + err.message);
30    } finally {
31      setDeleting(false);
32    }
33  };
34
35  return (
36    <div>
37      <h3>{mission.name}</h3>
38      <button onClick={handleDelete} disabled={deleting}>
39        {deleting ? 'Usuwanie...' : 'Usun misje'}
40      </button>
41    </div>
42  );
43}
Przejdź do CodeWorlds