Search code examples
reactjsmediawikimediawiki-api

How do I make API call to login?


I am using MediaWiki as my backend and I have it running on 'localhost/name'.

My login.js file:

import React, {useState} from 'react';
import axios from 'axios';

function Login()  {

    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');

    async function login() {
        console.log(username, password);

        let url = 'http://localhost/wikimedia/api.php';

        let params = {
            action: "query",
            meta: "tokens",
            format: "json",
            type: "login"
        };

        // fetch login
        const response = await axios.get(url + '?' + params + '&origin=*');

        console.log(response);

        let loginToken = response.data.query.tokens.logintoken
        let cookie = response.headers['set-cookie'].join(';');

        let body = {
            action: 'login',
            lgname: username,
            lgpassword: password,
            lgtoken: loginToken,
            format: 'json'
        }

        let bodyData = new URLSearchParams(body).toString();

        axios.post(url, bodyData, {
            headers: {
                Cookie: cookie,
            }
        }).then(response => {

            let cookie = response.headers['set-cookie'].join(';')
            console.log(response.data);
        })
    }

    return (
      <div>
        <h1>Sign In</h1>
        <input 
            type="text"
            onChange={(e) => setUsername(e.target.value)}
            placeholder="username"
        />
        <br/>
        <input
            type="password"
            onChange={(e) => setPassword(e.target.value)}
            placeholder="password"
        />
        <br/>
        <button onClick={login} type="submit">Login</button>
      </div>
    )
  };
  
  export default Login;

However, I'm getting the below response which is not what is expected according to the documentation:

{
    "data": "a-bunch-of-irrelevant-stuff",
    "status": 200,
    "statusText": "OK",
    "headers": {
        "cache-control": "private, must-revalidate, max-age=0",
        "content-language": "en",
        "content-type": "text/html; charset=utf-8",
        "expires": "Thu, 01 Jan 1970 00:00:00 GMT",
        "mediawiki-login-suppressed": "true"
    },
    "config": {
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        },
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "env": {},
        "headers": {
            "Accept": "application/json, text/plain, */*"
        },
        "method": "get",
        "url": "http://localhost/wikimedia/api.php?[object Object]&origin=*"
    },
    "request": {}
}

So far, I'm logging to the console the response of the first fetch -> token, but I'm not getting the response as expected:

{
    "batchcomplete": "",
    "query": {
        "tokens": {
            "logintoken": "9ed1499d99c0c34c73faa07157b3b6075b427365+\\"
        }
    }
}

Solution

  • You are getting a CORS error. See https://www.mediawiki.org/wiki/API:Cross-site_requests on how to make CORS requests to the MediaWiki API.