1

I have a message method in which triggers when i click submit button on my form. but i am unable to access the url in my node rest api, i am trying to access the url by "req.body.url" which returns an undefined, when i see what is in req.body nothing is present. I have done this using axios it works fine help me in using fetch

    message(event){
       event.preventDefault();
           const uri = this.state.short.url;
             fetch("http://localhost:3000/messages", {
              method: "post",
              body: {url: uri}
              })
            .then(function(data) {
          console.log("Request succeeded with  response", data);
           })
       .catch(function(error) {
           console.log("Request failed", error);
         });
    }
3
  • You might need to add a little more information. For example where is the code that's trying to access req.body.url. Commented Aug 24, 2018 at 5:08
  • i am accessing the req.body.url in REST API (in nodejs) Commented Aug 24, 2018 at 5:21
  • convert js object to a JSON before assigning to body? like body: json.stringify({url}) Commented Aug 24, 2018 at 5:24

3 Answers 3

4

In your fetch you need to specify Json and also stringing your json like so:

body: JSON.stringify({ url: uri }),
 headers:{
   'Content-Type': 'application/json'
}
Sign up to request clarification or add additional context in comments.

5 Comments

@ArupRakshit I don't think you're right. Passing headers and stringifying JSON are still necessary.
When posting, the client states what the content type of it’s body is. How is stringify not required?
Axios does some stuff itself but the OP uses fetch though.
@ChrisCousins Opps.. I am still reading it as 'axios', never used fetch, so I am not aware of... need a coffee, still awaking .
Ha yeah no worries, axios is great!
1

Without more information from you, I am guessing this is what you wanted:

fetch("http://localhost:3000/messages", {
    method: "post",
    body: JSON.stringify({url: uri})
    })
.then(function(response) {
    if(response.ok){
        return response.json();
    }{
        throw new Error("Post Failed")
    }
}).then(function(responseBody){
    console.log(responseBody.uri)
})
.catch(function(error) {
    console.log("Request failed", error);
});

Here's a runnable version that is very similar. It uses a service that just echos data back for testing.

    fetch("http://httpbin.org/post", {
        method: "POST",
        body: JSON.stringify({url: "test"})
    })
    .then(function(response) {
      if(response.ok){
        return response.json();
    }{
        throw new Error("Post Failed")
    }
}).then(function(responseBody){
    console.log(responseBody)
})
.catch(function(error) {
    console.log("Request failed", error);
});

2 Comments

thanks for the ur reply but it is not working i am getting Request failed TypeError: Failed to fetch
@VedaVyas I updated my answer to include JSON.stringify for the body and a runnable version that you can use for comparison.
0
const options = {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ url: uri})
};

fetch("http://localhost:3000/messages", options)
  .then(response => response.json())
  .then(data =>console.log(data));
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.