Utilizing Vue to send information to the POST function

I am encountering an issue with passing data to the Vue.js post method. I am using vue-resource and according to the documentation, it should be structured like this:

this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

When I try to add a header, everything works smoothly (the server reads the header correctly) for example:

 this.$http.post(
      'http://localhost:8081/login', 
      {
        headers: {
          'Accept': 'application/json'
        }
      });

However, when I attempt to include any data, things start going wrong. For instance, I tried:

this.$http.post(
      'http://localhost:8081/login',
       {username: 'admin'},
      {
        headers: {
          'Accept': 'application/json'
        }
      });

Or defining some data and including it like this:

this.$http.post(
      'http://localhost:8081/login', 
       this.data,
      {
        headers: {
          'Accept': 'application/json'
        }
      });

In both cases, the body section is always empty - I checked the body data from the request using:

 body = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));

The issue probably lies within the vue.js code as sending requests from Postman works without any problems. What steps should I take to resolve this?

Answer №1

Have you attempted sending a post request without including the third argument when using post?

this.$http.post('url', {something: "string"})
  .then ((res)=> console.log (res.body))
  .catch ((error)=> console.log(error))

This method has been successful for me...

Also, ensure that you are correctly receiving the request data on the backend. It appears to be in Python and I may not fully understand its workings.

Answer №2

If you're looking to send multiple JSON values, here is an example:

const vm = new Vue({
  el: '#app',
  data: {
    email: '',
    password: ''
  },
  methods: {
    getPosts() {
      return axios.post('http://127.0.0.1:5000/login',
        { email: this.email,
          password: this.password
        },
        { headers: {
        'Content-type': 'application/json',
        }
      }).then((response) => {
        console.log('email: ' + this.email);
        console.log('password: ' + this.password);
      }).catch( error => { 
        console.log('error: ' + error); 
      });
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="email" name="email" v-model="email">
  <input type="password" name="password" v-model="password">
  <button v-on:click="getPosts()">Login</button>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Making modifications to the state within a modal dialogue box

I am developing a note-taking application where users can write a title and note, and when they click submit, the note is displayed on the page. I want to implement an editing feature where clicking on the edit button opens a modal with the user's tit ...

JQuery not properly validating inputs with required attributes after creation

I am currently developing a contact form that includes an "alternative address" <div id='alt'> with toggleable visibility. Inside this div, there is a required <input> field. I encountered an issue where toggling #alt twice (thus hidi ...

creating an HTML table from JSON data using a specific key

In this json file, I am looking to create separate tables based on the IDs provided. For example, ID: "50" should be displayed in one table, while ID: "57" should be shown in another table within the same context. { "version": "5.2", "user_type": ...

What is the best way to incorporate a JavaScript library into a Vue3 project?

Trying to incorporate Leaflet into a Vue 3 project has presented some challenges for me. I require assistance in integrating a pure JS library with a Vue project, and I am uncertain if it is feasible without using a dedicated NPM package. After following t ...

Looking to resolve a module-specific error in Angular that has not been identified

While practicing Angular, I encountered an error during compilation: Module not found: Error: Can't resolve './app.component.css' in 'D:\hello-world-app\src\app' i 「wdm」: Failed to compile. This is my app.compo ...

How to verify that the user is using the most up-to-date version of the application in React Native

Currently, I am focused on the application and have implemented API endpoints that return the latest version along with information on whether the update is mandatory. Within the application flow, a GET request is sent to these API endpoints to check the ...

Detecting attribute changes in AngularJS directivesGuide to detecting changes in attributes within Angular

Combining jquery ui and angularjs in my project has been a great experience. I have created a custom directive as shown below. app.directive('datepicker', function() { return { link: function (scope, element, attrs) { elem ...

Database not receiving input data from AngularJS form submission

Having some trouble saving form data to the database using angularjs. Not sure what I'm doing wrong. Here's my HTML form: <form id="challenge_form" class="row" > <input type="text" placeholder="Challenge Name" ng-model="ch ...

Printing content to an HTML page using Node.js

I'm seeking advice on using Node JS, AJAX, and other related technologies. My goal is to display the content of a JSON file on my HTML page. While I've been successful in saving new objects to the JSON file, I'm struggling to find an effecti ...

Implementing color transitions in javascript

Everyone talks about transitioning things in CSS, but have you ever thought about transitioning background colors in JavaScript? I'm currently working on a function that changes the background color of a div with the id of ex1 to green. However, I&apo ...

What advantages does the Step function (AWS) offer compared to setTimeout (Javascript) for scheduling tasks?

I am currently in the process of developing an API service that allows any client to provide me with their HTTP request along with the desired time in seconds for execution. I have considered two potential approaches to achieve this: Utilizing a lambda f ...

The Ajax request is failing to execute properly on newly appended elements

My comment system allows users to post comments which are then appended to the existing ones. Whenever a user hovers over a comment, a 'delete' button appears. Clicking on the delete button prompts a confirm dialog and upon confirmation, an ajax ...

Obtain the value of an element from the Ajax response

Just starting out with Jquery and Ajax calls - here's what I've got: $(document).ready(function () { $.ajax({ type: "GET", url: "some url", success: function(response){ console.log(response); } }) }); Here's the ...

What is the best way to prevent duplicates in a Material-UI dropzone area?

Currently, I am utilizing the Material-UI Dropzone component from https://yuvaleros.github.io/material-ui-dropzone/ and my goal is to prevent users from uploading duplicate files that have been previously uploaded. I attempted using an onchange function t ...

Tips for utilizing props in a Vue component

When trying to incorporate a prop into a computed value, I encounter the following error: [Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined" found in ---> at src/cmps/space-details/space-imgs.vue at src/pa ...

Eliminate viewed alerts by implementing a scrolling feature with the help of Jquery, Javascript, and PHP

My goal is to clear or remove notifications based on user scrolling. The idea is to clear the notification once the user has seen it, specifically in a pop-up window for notifications. I am relatively new to Javascript/jQuery and feeling a bit confused abo ...

Transforming a string into an array containing objects

Can you help me understand how to transform a string into an array of objects? let str = `<%-found%>`; let result = []; JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => ...

[Vue-ChartJS] Seeking out instructions on incorporating gradients with Vuex and the reactiveProps mixin (API data) has proven challenging

Issue Link to Codepen example: https://codesandbox.io/s/vyy0z2my33 If you want to track this issue, visit: https://github.com/apertureless/vue-chartjs/issues/473 I have a project with a datepicker that triggers chart rerendering based on the selecte ...

Avoiding unnecessary re-renders of a parent component caused by a child component

I'm facing rendering problems and would greatly appreciate any assistance. I attempted to use useMemo and useCallback, but it resulted in the checkbox breaking. Within a component, I am displaying information from an object. Let's consider the fo ...

Experiencing issues with Errors when Targeting ES5 in Angular2 TypeScript?

In my development environment, the npm version is 3.10.10, and I want to create a new Angular2 project from scratch. When I try running npm install angular2 --save I encounter this error message: Error Image After referring to this answer which recomm ...