Juliette
Juliette

Reputation: 4439

path variables in react api call

I have an API that responds to an API call like below in Postman: Postman

The body is just

"username": "bobmarley"

How can I replicate this in my React/Next project?

Here is what I currently have:

export async function getUser(data) {
  
  const response = await fetch(`http://localhost:4000/users/:username`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
  })

  var response_data = await response.json();

  return(response_data);
}

How can I pass these path variables like in Postman too?

UPDATE

I implemented changes like comments suggested but came across issues:

export async function getUser(data) {

  const username = data
  const response = await fetch(`http://localhost:4000/users/${username}`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({username: username})
  })
  var response_data = await response.json();
  
  return(response_data);
}

This throws an error:

http://localhost:4000/users/bobmarley 404 (Not Found)

Not sure what to do?

UPDATE 2

I changed POST to GET but I got this error:

TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

I had GET in postman with the body below and it worked fine.

{
    "username": "bobmarley"
}

Upvotes: 1

Views: 3848

Answers (3)

user10593684
user10593684

Reputation:

The others got it, so just piggy-backing here.

Your API should be parsing the query string. That is, it looks like you've setup your API to need to look at the /:username part of the query string. Alternatively, you could pass it in the body, but that's outside the scope of your question. Here's an example, given your constraints.

export async function getUser({ username = 'bobmarley', ...rest }) {
  
  const response = await fetch(`http://localhost:4000/users/${username}`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(rest)

  });

  const response_data = await response.json();

  return response_data;
}

Unless you're passing other data in the body, you can destructure the data argument to its username property. If you are passing or require other body data, though, make sure your API endpoint is setup to deal with that type of data, too (I left the JSON.stringify part, for reference).

Upvotes: 1

fortunee
fortunee

Reputation: 4352

The :username is called a request parameter, Postman parses it for you behind the scene when you specify the value within those boxes.

However, working with React, you need to specify the value of the username in your fetch URL.

So it should look like this:

http://localhost:4000/users/bobmarly

As opposed to this

http://localhost:4000/users/:username

So if you have the username in the data you're passing into the getUser() function then specify it in the fetch URL using template strings in javascript.

Like this

const username = data.username || 'bobmarley';

const response = await fetch(`http://localhost:4000/users/${username}`, {
  ...
})

Upvotes: 1

Jorge Kunrath
Jorge Kunrath

Reputation: 1006

You would have to pass it in in the string itself, like:

export async function getUser(data) {

  const username = data.username //fake, but something like that i guess
  
  // and then use template string notation `regular string ${jsInterpolation}`
  const response = await fetch(`http://localhost:4000/users/${username}`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(data)
  })
  var response_data = await response.json();

  return(response_data);
}

Upvotes: 1

Related Questions