How to POST (and not GET) using Vue.js Axios and URLSearchParams


Login or Register to Reply

 
Thread Tools Search this Thread
# 1  
How to POST (and not GET) using Vue.js Axios and URLSearchParams

After days of struggle with examples on the net I had Googled so much that all my links were purple.

It turns out that there is some problem in Axios for Vue.js and the documentation and examples on 99.342 percent of the web tutorial sites are wrong. This leads me to believe that there are a lot of "cut-and-paste" tutorials and "experts" out there in netland (especially true on Stack Exchange, so I have seen recently).

Anyway, to make a long story, short. Here is the proper way to create a POST request using Axios:

CORRECT:

Code:
async function login() {
  let isValidForm = await this.$validator.validateAll();
  if (!this.user.login_username || !this.user.login_password) {
    this.login_status = true;
    this.status = "All Login Fields Are Required";
    return false;
  } else if (!isValidForm) {
    return false;
  }
  this.status = "Processing Login ...";
  this.login_status = true;
  const url = "https://www.examplesite.com/dothelogin.php";

  const params = new URLSearchParams();
  params.append("login_username", this.user.login_username);
  params.append("login_password", this.user.login_password);
  params.append("cookieuser", 1);
  params.append("do", "login");
  params.append("version", this.$store.state.version);

  const config = {
    headers: {
      "Content-Type": "application/json"
    }
  };
  this.axios.post(url, params).then(
    response => {
      this.$store.commit("setloginstatus", response.data);
      if (response.data.status == "success") {
        this.login_status = true;
        this.status = "Login Success";
        window.open(success, "_self");
      } else if (response.data.status == "badlogin_strikes") {
        this.login_status = true;
        this.status = "Login Failure, Please try again!";
      } else {
        this.login_status = true;
        this.status = "Login Failure, Please try again!!";
      }
    },
    error => {
      console.log(error);
      this.login_status = true;
    }
  );
}

DOCUMENTED BUT INCORRECT:

Code:
async function login() {
  let isValidForm = await this.$validator.validateAll();
  if (!this.user.login_username || !this.user.login_password) {
    this.login_status = true;
    this.status = "All Login Fields Are Required";
    return false;
  } else if (!isValidForm) {
    return false;
  }
  this.status = "Processing Login ...";
  this.login_status = true;
  const url = "https://www.examplesite.com/dothelogin.php";

  const params = {
  login_username: this.user.login_username,
  login_password: this.user.login_password,
  cookieuser: "1",
  version:  this.$store.state.version,
  do: "login"
  };


  const config = {
    headers: {
      //"Content-Type": "application/x-www-form-urlencoded"
      "Content-Type": "application/json"
    }
  };
  this.axios.post(url, params).then(
    response => {
      this.$store.commit("setloginstatus", response.data);
      if (response.data.status == "success") {
        this.login_status = true;
        this.status = "Login Success";
        window.open(success, "_self");
      } else if (response.data.status == "badlogin_strikes") {
        this.login_status = true;
        this.status = "Login Failure, Please try again!";
      } else {
        this.login_status = true;
        this.status = "Login Failure, Please try again!!";
      }
    },
    error => {
      console.log(error);
      this.login_status = true;
    }
  );
}

The problem is that this code, which works for GET, will not work for POST:

Code:
  const params = {
  login_username: this.user.login_username,
  login_password: this.user.login_password,
  cookieuser: "1",
  version:  this.$store.state.version,
  do: "login"
   };

However, I could get the "not working" method above to work (POST) only if I changed the content-type:

Code:
"Content-Type": "application/x-www-form-urlencoded"

But in Axios, this mangles the JSON POST data so much that I had to write some very kludgy PHP string processing code to get the very mangled POST request string converted to a proper, and useable, $_POST array.

Note: I was going to post the "mangled POST processing PHP code" but I deleted that code out of my script when I finally got the POST request to work and am lazy to go to GitHut and retrieve that "bad code" from the repo, LOL

So, if I use the URLSearchParams() method to create the POST params (not in the docs on Vue.js or Axios), it works fine, 'POST, ing' as JSON.

Code:
  const params = new URLSearchParams();
  params.append("login_username", this.user.login_username);
  params.append("login_password", this.user.login_password);
  params.append("cookieuser", 1);
  params.append("do", "login");
  params.append("version", this.$store.state.version);

There are 100s of wrong Axios POST examples tutorials on the net and the documentation is also incorrect because the documentation shows the POST and GET request using the same param object for both POST and GET, but that will not work and I had to dissect every step of the client-server POST process from the JS inside Axios to the heart of PHP HTTP request processing to find the solution. What a waste of time, LOL.....

To help anyone else who is using Axios in Vue.js, I post this correct example solution for the Axios POST method so to help anyone who might struggle for hour and hours to debug and get a mangled Axios POST request to work. Just use URLSearchParams() and save yourself days of time.
These 4 Users Gave Thanks to Neo For This Post:
Login or Register to Reply

|
Thread Tools Search this Thread
Search this Thread:
Advanced Search

More UNIX and Linux Forum Topics You Might Find Helpful
The State of Vue.js
Neo
Here is very good video from Evan You, founder of Vue.js, on the state of Vue.js State of Vuenation with Evan You Here is a nice PDF report on Vue.js Update State of Vue.js Report Vue.js is now the second most starred project on GitHub, recently surpassing Bootstrap. These two...... Web Development
0
Web Development
Vue.js Steam Chat
Neo
This Vue.js chat component installed easily: npm i --save vue-steam-chat I was able to set it up and change the background color in the component css file to match the forums in seconds: https://www.unix.com/members/1-albums225-picture1162.png <template> <div style="height: 600px;...... Web Development
17
Web Development
Vue JS 2 Tutorial by The Net Ninja: A Recommended Vue.js Video Tutorial Series
Neo
A number of people have asked me how to get started with Vue.js and my reply before today was to Google "Vue.js". That has changed and my recommendation to anyone who wants to learn the fastest growing, easiest to learn and use Vue.js web dev framework is to watch this video tutorial series: ...... Web Development
0
Web Development
Simple Vue.js Component to Redirect to External Web Page Using Vue Router
Neo
Vue Router has some quirks and on of the quirks is that it is not reliable when adding external links using the vue-router library. After struggling with many solutions, I have found that creating a simple Vue.js component like this one seems to work the best (so far): Component Example: ...... Web Development
0
Web Development
Some Thoughts on Vue.js at UNIX.com
Neo
Recently, have been learning Vue and, as always, learning-by-doing, which means writing code for real-world applications. In this process, I have learned something that is not really mentioned in the majority of online Vue tutorials. Basically, when you create a Vue instance in your browser,...... Web Development
0
Web Development
UNIX and Linux

Unix (trademarked as the UNIX certification mark) is a very mature family of multitasking, multiuser computer operating systems that evolved from the original AT&T Unix. Unix development starting in the 1970s by legendary Bell Labs programmers Ken Thompson, Dennis Ritchie, and others. Unix was first targeted for the Bell System and AT&T licensed Unix to outside parties. In the 1970s time period, this lead to a variety of for-profit as well as not-for-profit Unix variants.
In the early days, this included the University of California, Berkeley (BSD), Microsoft (Xenix), IBM (AIX), and Sun Microsystems (Solaris). In the early 1990s, AT&T sold their Unix rights to Novell. In 1995 Novell sold their Unix business to the Santa Cruz Operation (SCO). The UNIX trademark was passed to The Open Group, a "neutral" industry consortium. The Open Group promoted the use of the UNIX trademark for certified operating systems that comply with the Single UNIX Specification (SUS). In 2014 Apple's macOS became the Unix version with the largest global install base and macOS remains the largest Unix-user base today.
Linux is a family of open source Unix-like operating systems based on the Linux kernel. The Linux kernel is an operating system kernel first released by Linus Torvalds on 17 September 1991. Linux distributions include the Linux kernel, system software and libraries. Popular free open source Linux distributions include Debian, Fedora, and Ubuntu. Commercial Linux distributions include Red Hat Enterprise Linux and SUSE Linux Enterprise Server. Linux may be freely modified and redistributed. Anyone on the planet may create a Linux distribution for any purpose.
Please enjoy and help our forum community by "showing your work" and posting your code, even when your code is not working as expected. To help others help you, please wrap your code blocks, sample input, sample output, error messages, and other data in CODE tags and wrap your short commands and short data objects in ICODE tags. We were all beginners in the beginning. If you have any questions about how to register or how to post, please contact us in Live Chat. Thank you and enjoy this "forever free" technical support community for UNIX, Linux and computer information technology in general.