Home > Net >  Use axios post to access mediawiki API
Use axios post to access mediawiki API

Time:10-22

I have been using MediaWiki API for some time using properly formatted URLs, but i need to access a wiki with a required login.

I tried using fetch to make the request, and also axios, and the result is the same: the HTML page of the API, the same I would get if i just put the URL of the api in a browser.

My axios call is this:

axios.post('/wiki/api.php', {
   logintoken: "this. Token",
   action: "clientlogin",
   username: "xxxxx",
   password: "yyyyyy",
   loginreturnurl: "http://localhost/",
   format: "json"
}).then(function (response) {
   console.log(response. Data);
})

It is as if the post request is simply not made. I tested using the Wikipedia api, and the result is the same.

Any help?

CodePudding user response:

I believe you should add a ?format=json parameter? Even though it is a post request

CodePudding user response:

In the end it all came down to the fact that the MediaWiki API was expecting the parameters in the application/x-www-form-urlencoded format, and not application/json or text/plain ones.

When I changed that, I was able to login as expected, regardless of using axios or simply fetch.

The final code looks like this (token obtained via another API call):

const opts = {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: new URLSearchParams({
          "logintoken": this.token,
          "action": "clientlogin",
          "username": "username",
          "password": "password",
          "loginreturnurl": "http://localhost/",
          "format": "json"
        })
      };
      const res = await fetch('/wiki/api.php', opts).
  • Related