0

I have an API with 2 endpoints: /one/ and /two/. They are associated with two buttons on my React app. When a user logs in to the frontend application I want any calls to these API endpoints to use the same "session". I'm not sure if my terminology is correct here, but here's how I would do it in python:

import requests
endpoint1 = "http://127.0.0.1:8000/one/"
endpoint2 = "http://127.0.0.1:8000/two/"
session = requests.Session()
session.post(endpoint1, json={"key":"foo"})
session.post(endpoint2, json={"key":"bar"})

In this example, the API knows that both requests came from the same session. I would like to repeat this behaviour in Javascript but I don't know how.

Here is how I'm currently calling the endpoints:

export function postOne(someData) {
    return fetch(
        'http://127.0.0.1:8000/one/',
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                key: someData
            }),
        }
    ).then(response => response.json())
}

export function postTwo(someData) {
    return fetch(
        'http://127.0.0.1:8000/two/',
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                key: someData
            }),
        }
    ).then(response => response.json())
}

Using this code, when I call /one/ and /two/ from the frontend, the API sees them as coming from different sessions. How can I modify the fetch calls to use the same session?

Dan
  • 1,575
  • 1
  • 11
  • 17
  • 1
    Possible duplicate: Does this answer your question? [Fetch API with Cookie](https://stackoverflow.com/questions/34558264/fetch-api-with-cookie) – Mushroomator Sep 20 '22 at 22:26

0 Answers0