0

Post Functionality in Vue.js is returning a null value.

The API Call is local to my machine on a different port. The GET Functionality work as expected. The POST functionality doesn't work as expected only returns null.

fetch('http://localhost:8080/Exercise/lists/add', {
                method: 'POST',
                headers: {
                    "Content-Type" : "application/json",
                },
                body: JSON.stringify(this.user)
            })
            .then((response) => {
                if(response.ok) {
                    console.log('Response is Ok.');
                }
            })
            .catch((err) => {console.log(err)});
        }

Expected to add a user. Rather returns a null value. Console.log output here..

PostMan "post" service

PostMan "post" service working..

2 Answers2

0

According to this site, the body of the post request is formated like 'foo=bar&lorem=ipsum'. But in your case the data are a JSON stringified object like "{"x":5,"y":6}". This could make a difference for your backend.

Also you can control the requests between your browser and the backend with the browser's network insepector (for Firefox it's Ctrl+Maj+J, then Network tab). It will tell you what data you send to your server and what is the response.

Dali
  • 344
  • 1
  • 10
0

You should use Axios for API calls in Vue. You can find the Axios reference from the documentation https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html.

According to the documentation from Google when you use the POST request method you need to pass body and the image you uploaded shows you used firstName param. So either change your API and use body to get the first name or you can do something like this:

fetch('http://localhost:8080/Exercise/lists/add?firstName='+JSON.stringify(this.user), {
                method: 'POST',
                headers: {
                    "Content-Type" : "application/json",
                },
                body: ''
            })
            .then((response) => {
                if(response.ok) {
                    console.log('Response is Ok.');
                }
            })
            .catch((err) => {console.log(err)});
        }
tony19
  • 125,647
  • 18
  • 229
  • 307
Shubham Sharma
  • 205
  • 2
  • 13
  • Don't use a POST request if you don't put anything in the body https://stackoverflow.com/questions/611906/http-post-with-url-query-parameters-good-idea-or-not – Dali Jul 02 '19 at 11:26