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


 
Thread Tools Search this Thread
Top Forums Web Development How to POST (and not GET) using Vue.js Axios and URLSearchParams
# 1  
Old 03-17-2019
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 Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. Web Development

The State of Vue.js

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... (0 Replies)
Discussion started by: Neo
0 Replies

2. Web Development

Vue.js Steam Chat

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;... (17 Replies)
Discussion started by: Neo
17 Replies

3. Web Development

Vue JS 2 Tutorial by The Net Ninja: A Recommended Vue.js Video Tutorial Series

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: ... (0 Replies)
Discussion started by: Neo
0 Replies

4. Web Development

Simple Vue.js Component to Redirect to External Web Page Using Vue Router

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: ... (0 Replies)
Discussion started by: Neo
0 Replies

5. What is on Your Mind?

My Charts in the Prototype Vue.js UserCP

Yea.... something I thought would take me an hour ended up taking most of the day. Well, it's not like those YT video tutorials where it take a week or more to make a video and the guys (gals) make it look so easy. But having said that, I'm happy to share with forum members the first "My... (6 Replies)
Discussion started by: Neo
6 Replies

6. Web Development

Some Thoughts on Vue.js at UNIX.com

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,... (0 Replies)
Discussion started by: Neo
0 Replies

7. Web Development

Turning jQuery Code into Vue.js

The following is some code I am working on the replace our navbar (someday) with a Vue component. Vue.component("unix-navbar", { template: `<div class="neo-table-border vuenavbar"><div class="flex-item" style="margin-bottom:10px;padding-top:13px;"><a class="vuenavbarhome"... (19 Replies)
Discussion started by: Neo
19 Replies

8. HP-UX

HPUX 10.20 and fx5 which patches for vue

Which patches or bundles must be installed to use an fx5 grafic in a HP C3600 WS. We use 10.20 from Dez 99 thanks for :confused: (0 Replies)
Discussion started by: dlanor
0 Replies

9. HP-UX

HP VUE Messaginbg system could not be started

hi guys..its been a while since my last post... a friend of mine has a problem with their HP Openview and has the following error: The HP VUE messaging system could not be started. To correct the problem: 1. Choose to return to the login-screen. 2. Select failsafe session.... ... ... (2 Replies)
Discussion started by: inquirer
2 Replies
Login or Register to Ask a Question