#How to send data to a JSON endpoint

1 messages · Page 1 of 1 (latest)

golden bone
#

I have a piece of data, like so: let jobPagesCount = 1 (on a client-side) and I need to send it over to an index.json.ts file, so I can use it there for fetching new data. This is supposed to happen when a user clicks a button. I tried:

button?.addEventListener('click', async () => {
    return await fetch('/index.json', {
      method: 'POST',
      body: JSON.stringify({ jobPagesCount }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
 })

but I got an error in the console that says: "POST http://localhost:4321/index.json 404 (Not Found)", even though the endpoint seems to work correctly because when I type "http://localhost:4321/index.json" in the address bar, I can see the data that are currently fetched in there.

What am I doing wrong?

steady haloBOT
#

Hi @golden bone. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the information provided in the extracts, it seems like you're trying to send a POST request to an Astro endpoint. In Astro, you can define custom endpoints by adding a .js or .ts file to the /pages directory. The file extension will be removed during the build process, so the name of the file should include the extension of the data you want to create. For example, src/pages/data.json.ts will build a /data.json endpoint.

In your case, you're trying to send a POST request to /index.json, so you should have a file named index.json.ts in your /pages directory. Inside this file, you need to export a POST function that handles the incoming request. Here's an example from the extracts:

export const POST: APIRoute = ({ request }) => {
  // handle the request here
  return new Response(JSON.stringify({ message: "This was a POST!" }))
}

In this example, the POST function is exported from the index.json.ts file. When a POST request is made to /index.json, this function will be called.

If you're still getting a 404 error, it could be because you haven't defined a POST function in your index.json.ts file, or the file doesn't exist in the correct location. Make sure the file is in the /pages directory and that it exports a POST function.

For more information, you can refer to the Astro documentation on endpoints (https://docs.astro.build/en/core-concepts/endpoints/).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@golden bone kapa.ai is still learning and improving, please let us know how it did by reacting below

golden bone
#

@steady halo
Ok, I didn't know I needed another POST request inside my index.json.ts file. I copied your code, but I added an additional console.log, to find the data I'm trying to send. To sum up:

// index.astro, client-side javascript
button?.addEventListener('click', async () => {
    return await fetch('/index.json', {
      method: 'POST',
      body: JSON.stringify({ jobPagesCount }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
 })
// index.json.js
export const POST = ({ request }) => {
  console.log(request.body); // returns: ReadableStream { locked: false, state: 'readable', supportsBYOB: false }
  return new Response(JSON.stringify({ message: "This was a POST!" }))
}

export const GET = async ({ request }) => {
  // here I need this piece of data to be able to fetch new data
}

So, how can I get my data inside this POST request inside the index.json.ts file and pass it to the GET request?

steady haloBOT
#

Let me check the knowledge base for you. One moment! :books:

#

In your POST function, you're trying to log request.body, which is a ReadableStream. To read the data from the stream, you need to use the text() or json() methods, which return a promise that resolves with the data.

Here's how you can read the data from the request body:

export const POST: APIRoute = async ({ request }) => {
  const data = await request.json(); // if the body contains JSON data
  console.log(data);
  return new Response(JSON.stringify({ message: "This was a POST!" }))
}

However, passing data from a POST request to a GET request in the same endpoint is not straightforward. These requests are independent of each other and don't share any state.

A common way to share data between requests is to use a database or some form of persistent storage. When you receive a POST request, you can store the data, and then retrieve it when you receive a GET request.

If you need to fetch new data based on the jobPagesCount value, you could consider including this value in the URL or query parameters of the GET request. This way, you can retrieve the value in the GET function and use it to fetch the data.

For more information, you can refer to the Astro documentation on endpoints (https://docs.astro.build/en/core-concepts/endpoints/).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: