skip to Main Content

I have a problem with req.body.thread_id = thread.id, when I call it in, it’s undetermined

app.post('/api/assistant/start', async (req, res) => {     
    const thread = await client.beta.threads.create()     
    console.log(""thread_id": " + thread.id);     
    req.body.thread_id = thread.id     
    return res.json(""thread_id": " + thread.id) 
});
app.post('/api/assistant/chat', async (req, res) => {
    const data = req.body.thread_id
    console.log(data)
    return res.json("Finish")
})

Output:

undefined

I use node.js and express with body-parser

Can you suggest another way to pass a variable between functions?

I’ve tried different variations of save call and saves. Always the same output.

2

Answers


  1. you are passing the variable through the body and this is wrong because the body is filled by the request so to solve it try thread.id here => req.thread_id = thread.id

    Login or Signup to reply.
  2. The issue you are encountering simply means that your body has no thread_id field.

    Since your POST operation :

    app.post('/api/assistant/start', async (req, res) => {     
        const thread = await client.beta.threads.create();     
        console.log(""thread_id": " + thread.id);     
        return res.json({thread_id: thread.id});
    });
    

    Is the one that creates the thread and sends its id back to the client. One way would be to call your endpoints from the client-side as in the following, to ensure that they are called in the correct sequence. And that thread_id is passed to the POST /api/assistant/chat endpoint:

    fetch('/api/assistant/start', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
    }).then(response => response.json())
      .then(data => {
          // Use `data.thread_id` in the next request
          fetch('/api/assistant/chat', {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/json',
              },
              body: JSON.stringify({ thread_id: data.thread_id }),
          }).then(/* handle response in the way you want*/);
      });
    

    The other post should remain as it is in your router:

    app.post('/api/assistant/chat', async (req, res) => {
        const data = req.body.thread_id;
        console.log(data); // Should now log the correct thread_id
        return res.json("Finish");
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search