69

Axios 0.17.1

.then(function (response) {
                console.log(response);
                //console.log(response.status);
                //It is an error -> SyntaxError: Unexpected token u in JSON at position 0 
                console.log(JSON.parse(response.data.error));
                console.log(response.data.error); //undefined.

The console.log of response is

{data: "{"error":"Name must be entered with more than one … NULL↵
["isPipe":protected]=>↵ NULL↵ }↵}↵", status: 203, statusText: "Non-Authoritative Information", headers: {…}, config: {…}, …} config : {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …} data : "{"error":"Name must be entered with more than one character."}object(Slim\Http\Response)#32 (5) {↵ ["status":protected]=>↵ int(200)↵ ["reasonPhrase":protected]=>↵ string(0) ""↵ ["protocolVersion":protected]=>↵ string(3) "1.1"↵ ["headers":protected]=>↵ object(Slim\Http\Headers)#33 (1) {↵
["data":protected]=>↵ array(1) {↵ ["content-type"]=>↵
array(2) {↵ ["value"]=>↵ array(1) {↵ [0]=>↵
string(24) "text/html; charset=UTF-8"↵ }↵
["originalKey"]=>↵ string(12) "Content-Type"↵ }↵ }↵ }↵ ["body":protected]=>↵ object(Slim\Http\Body)#31 (7) {↵
["stream":protected]=>↵ resource(59) of type (stream)↵
["meta":protected]=>↵ NULL↵ ["readable":protected]=>↵ NULL↵
["writable":protected]=>↵ NULL↵ ["seekable":protected]=>↵
NULL↵ ["size":protected]=>↵ NULL↵ ["isPipe":protected]=>↵
NULL↵ }↵}↵" headers : {content-type: "application/json;charset=utf-8"} request : XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status : 203 statusText : "Non-Authoritative Information" proto : Object

JSON.parse(response.data) as well as response.data.error -> Both are giving error. How can i read the data?

Slimframework 3.

$data = array('error' => 'Name must be entered with more than one character.');
        $newResponse = $response->withJson($data, 203);
        return $newResponse;
Mahesh
  • 1,503
  • 3
  • 22
  • 33
  • SyntaxError: Unexpected token u in JSON at position 0 – Mahesh Jan 02 '18 at 14:37
  • Check `console.log(response.data)` and see what the format is of the data object. Looking at your example output it looks like there is too many quotes `"` - `data: "{"error":"Name must be entered...` - this: `"{"error":"` looks strange – Nope Jan 02 '18 at 16:29
  • 1
    Verify whether the response you receinved is a valid JSON. If it is valid, axios will parse it to a JSON object. otherwise it will return you a plain string object. – Karthikeyan May 16 '21 at 12:15
  • do like this for axios .then((response)=> JSON.stringify(response.data)) .catch((error)=> JSON.stringify(error.response.data)) – Kashinath Sep 21 '22 at 06:12

12 Answers12

83

In Axios responses are already served as javascript object, no need to parse, simply get response and access data.

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
  • 9
    `console.log(response.data.error); //undefined` - I can log response.data But response.data.error is undefined. unable to use JSON.parse - it is giving me error. – Mahesh Jan 02 '18 at 14:41
  • 3
    This means that response.data EXISTS but do not have "error" key , can you post the output of response.data ? Usually when response.error is undefined simply means that the axios response has no errors. – Mosè Raguzzini Jan 02 '18 at 14:44
  • 1
    the yellow color box (content) is the console.log for response received from slimframework. - Please check i updated again. – Mahesh Jan 02 '18 at 14:46
  • can you post RAW output ? ES: console.log(response). If you are using chrome, I mean not the "preview" tab in network, but "response" tab. – Mosè Raguzzini Jan 02 '18 at 14:48
  • 1
    you should provide an example instead of saying _just do it_ – Joey Carlisle Dec 29 '21 at 17:51
  • This top rated answer is missing some info. Axios only converts valid JSON automatically. If the JSON contains an error Axios quietly fails the JSON parse and just serves a string. – wearego Jul 25 '23 at 15:38
30

Assuming the response from the server looks like this:

{"token": "1234567890"}

Then in Axios you can access it like this:

console.log( response.data.token )
Robert Reiz
  • 4,243
  • 2
  • 30
  • 43
7

As already written, Axios already returns JSON by default. Just use response.data as simple JS object.

However, following insight might help others: I had an issue that Axios returned the response as a string. When investigated I discovered that the server returned an invalid JSON (it was a static file server). When fixed the JSON format, Axios used JSON instead of string again.

MaMazav
  • 1,773
  • 3
  • 19
  • 33
  • 1
    I was also using a mocked JSON response, and it had an extra closing comma which was causing the parsing issue – muya_ Sep 30 '22 at 06:09
6

This happened to me because I wrote

import { Axios } from "axios"; // named export: problem
const instance = new Axios({ baseURL: "#####" }); // new Axios: problem

When it was supposed to be

import axios from "axios"; // default export: no problem
const instance = axios.create({ baseURL: "#####" }); // axios.create: no problem

Credits: https://github.com/axios/axios/issues/3419#issuecomment-1015921836

Glass Cannon
  • 394
  • 3
  • 9
5

you can simply get it as following,

ex:

{
    "terms": {

        "title": "usage",

        "message": "this is the usage message"

    }

}
 

when the response look like this,you can get it using "response.data",and so on....

.then(response => 
        console.log( response.data.terms.message)
        
  

Cheers !

janadari ekanayaka
  • 3,742
  • 2
  • 13
  • 17
3

I had a similar format response as the one in console log and my issue was that my .json file wasn't properly formatted. I was missing a comma. Post your json file to have a look.

Palle Due
  • 5,929
  • 4
  • 17
  • 32
KT-mongo
  • 2,044
  • 4
  • 18
  • 28
3

For some reason, in my case the JSON was properly formatted but was returned as string anyway. With this workaround I solved the issue.

// ...
return await this.axios_instance.request<T>({
    method,
    url,
    headers,
    params,
    transformResponse: (data) => JSON.parse(data), // <----------
    data,
});

Simply put, I explicitly told to transform the response using JSON.parse. For some reason this worked, while other answers didn't.

This worked for me!! Hope it helps.

saniales
  • 451
  • 3
  • 14
  • I made the same experience with django JSON serialized object from a query. dict object from django works without JSON.parse. – VengaVenga Jan 06 '23 at 21:50
2

axios by defualt convert response to JSON, you must use response.data instead of response

export const addPosts = () => async (dispatch) => {
await axios('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => dispatch({type: postActionTypes.POSTS, payload: response.data}))}
1

Here is sample code,

try {
  const res = await axios.get("/end-point");
  console.log("JSON data from API ==>", res.data);
} catch (error) {
  // handle error
}
Alish Giri
  • 1,855
  • 18
  • 21
0

I had a similar problem. As others have pointed out, axios reads the json as a js object and you can easily move through the hierarchy to get your field data.

However, for me axios did not want to read the json as an object and instead returned a string. The cause was that there was a hanging comma at the end of the json due to a previous row deletion in the file. So the file content wasn't valid json, and axios simply returned a string. Remove the comma, everything worked.

I would suggest to check the json for any incorrect syntax.

kumaheiyama
  • 704
  • 1
  • 13
  • 28
0

I had the same problem and I found that I was not reading data properly. Finally, I got a solution. try this.

my data was like:

response = [{"myname","Anup","age":23,"Education":"Graduation"}]

I was trying to retrieve data like(this was giving output undefined)

axios('https://apiurl.com')
.then((reponse)=>{
const recieved_Data=fetchdata.data;
console.log(recieved_Data.name);
})

Correct Approach:

axios('https://apiurl.com')
.then((reponse)=>{
const recieved_Data=fetchdata.data;
console.log(recieved_Data[0].name);
})

as you can see i have passed the index value of the array of my response recieved_Data[0].name And this gave me the correct output.

Vote me if this works for you.

Thanks!

Anup Kumar
  • 61
  • 3
-1

So I came across this post in search of an answer to my question. "How to access data in a json file returned by an api." Nonetheless, what worked for me at the end of the day was an answer to a similar question on stackoverflow to which the link is Axios. How to get error response even when api return 404 error, in try catch finally.

However, here is the code I used to access my error codes returned by my backend api. axios.get(/sanctum/csrf-cookie).then(response => { axios.post(api/register, registerInfo) .then(response => { console.log('This is the response: ' + response.data.errors); }).catch(error => { console.log('This is the error: ' + error.response.data.errors.name); }); });

DJBlom
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 03 '21 at 08:14