Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS AXIOS post doesn't work

I'm trying to submit a login form to an API, however, the API doesn't pass the post request test.

ReactJS Action:

/**
 * Sends login request to API
 */
export function login(email, password) {
    console.log('Credentials:', email, password)
    const request = axios.post(`${ROOT_URL}login/login`, 
        {
            email,
            password
        })
        .then((response) => console.log(response))
        .catch((error) => console.log(error));
}

Login function from api:

    public function actionLogin($credentials = [])
    {
        $request = Yii::$app->request;

        if ($request->post()) { 
            // handle the user login
        } else {
            return Json::encode(['status' => false, 'data' => 'error_no_request']);
        }
    }

Console logging the request Console logging the response - it's clear that it doesn't get through the request test.

Headers:

Response Headers
Access-Control-Allow-Origin:*
Connection:Keep-Alive
Content-Length:42
Content-Type:text/html; charset=UTF-8
Date:Wed, 20 Sep 2017 06:42:06 GMT
Keep-Alive:timeout=5, max=98
Server:Apache/2.4.18 (Win32) OpenSSL/1.0.2e PHP/7.0.8
X-Powered-By:PHP/7.0.8

Request Headers
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:56
Content-Type:application/json;charset=UTF-8
Host:127.0.0.1
Origin:http://localhost:8080
Referer:http://localhost:8080/login

enter image description here Console logging the request.

like image 778
Moldovan Andrei Avatar asked Sep 20 '17 06:09

Moldovan Andrei


1 Answers

Ok, so since the POST method doesn't work, I tried it with the GET method. And for some reason, it works. The action now looks like:

export function login(email, password) {
    const request = axios({
        headers: { 
            'content-type': 'application/json'
        },
        method: 'post',
        url: `${ROOT_URL}login/login`,
        params: {
            email,
            password
        }
    })
    .then((response) => response.data)
    .catch((error) => error);
}
like image 85
Moldovan Andrei Avatar answered Sep 24 '22 12:09

Moldovan Andrei